One-line list comprehension with different index using Python - python

I am creating a list in python in the following way:
new_points = [None] * 25
for point in points:
new_points[point.id] = point
I am wondering if this can be achieved by Python one-line list comprehension. Please note that each point has a unique id. Hence two points can never have same ids.

This sounds like you want to sort the list rather than use a comprehension.
new_points = sorted(points, key=lambda x:x.id)
The sorted function takes an iterable and a key function and returns a list. In this case the key function only needs to get the id.

I don't know of any way to populate random locations in a list with a one-liner. But if all you want is to be able to find a point by its id, you could use a dict in stead of a list:
new_points = {p.id: p for p in points}

Related

Putting Result of Multiplication in a List

I am trying to put a series of multiplications inside a list, I am using the code below:
listx = []
for i in range (2):
list = [(3*i)]
listx.append(list)
The problem is that this will put the two results inside two separate lists inside a lists, I just wants the floats to be inside the first list.
listx = []
for i in range (2):
listx.append(3*i)
Just use this one. There is no need to create another list for storing the result. You created another list to store the value and appended that list into your listx
You can also use list comprehensions. Basically it's the same with for cycles but it's much shorter and for simpler operations like yours it's easier to read.
listx = [i*3 for i in range(2)]
This should produce a single list with values multiplied by 3 as integers

How to add up values of the "sublists" within a list of lists

I have a list of lists in my script:
list = [[1,2]
[4,3]
[6,2]
[1,6]
[9,2]
[6,5]]
I am looking for a solution to sum up the contents of each "sublist" within the list of lists. The desired output would be:
new_list = [3,7,8,7,11,11]
I know about combining ALL of these lists into one which would be:
new_list = [27,20]
But that's not what i'm looking to accomplish.
I need to combine the two values within these "sublists" and have them remain as their own entry in the main list.
I would also greatly appreciate it if it was also explained how you solved the problem rather than just handing me the solution. I'm trying to learn python so even a minor explanation would be greatly appreciated.
Using Python 3.7.4
Thanks, Riftie.
The "manual" solution will be using a for loop.
new_list = []
for sub_list in list:
new_list.append(sum(sub_list))
or as list compherension:
new_list = [sum(sub_list) for sub_list in list]
The for loop iterates through the elements of list. In your case, list is a list of lists. So every element is a list byitself. That means that while iterating, sub_list is a simple list. To get a sum of list I used sum() build-in function. You can of course iterate manually and sum every element:
new_list = []
for sub_list in list:
sum_val = 0
for element in sub_list:
sum_val = sum_val + element
new_list.append(sum_val)
but no need for that.
A better approach will be to use numpy, which allows you to sum by axis, as it looks on list of lists like an array. Since you are learning basic python, it's too soon to learn about numpy. Just keep in mind that there is a package for handling multi-dimensions arrays and it allows it perform some actions like sum on an axis by your choice.
Edit: I've seen the other solution suggest. As both will work, I believe this solution is more "accessible" for someone who learn to program for first time. Using list comprehension is great and correct, but may be a bit confusing while first learning. Also as suggested, calling your variables list is a bad idea because it's keyword. Better names will be "my_list", "tmp_list" or something else.
Use list comprehension. Also avoid using keywords as variable names, in your case you overrode the builtin list.
# a, b -> sequence unpacking
summed = [a + b for a, b in lst] # where lst is your list of lists
# if the inner lists contain variable number of elements, a more
# concise solution would be
summed2 = [sum(seq) for seq in lst]
Read more about the powerful list comprehension here.

Initialize a list using inline for loop

I am initializing my list object using following code.
list = [
func1(centroids[0],value),
func1(centroids[1],value),
....,
func1(centroids[n],value)]
I am trying to do it a more elegant way using some inline iteration. Following is the pseudo code of one possible way.
list = [value for value in func1(centroids[n],value)]
I am not clear how to call func1 in an iterative way. Can you suggest a possible implementation?
For a list of objects, Python knows how to iterate over it directly so you can eliminate the index shown in most of the other answers,
res = [func1(c, value) for c in centroids]
That's all there is to it.
A simple list comprehension consists of the "template" list element, followed by the iterator needed to step through the desired values.
my_list = [func1(centroids[0],value)
for n in range(n+1)]
Use this code:
list = [func1(centroids[x], value) for x in range(n)]
This is called a list comprehension. Put the values that you want the list to contain up front, then followed by the for loop. You can use the iterating variable of the for loop with the value. In this code, you set up n number(s) of variable(s) from the function call func1(centroids[x], value). If the variable n equals to, let's say, 4, list = [func1(centroids[0], value), func1(centroids[0], value), func1(centroids[0], value), func1(centroids[0], value)] would be equal to the code above

Sort Coordinates in Python

I have a list of coordinates like:
[44.64,-123.11;38.91,-121.99;40.35,-122.28;43.21,-123.36;41.77,-122.58;37.77,-122.42]
I need to sort this list. Any suggestions ?
EDIT:
Sorry for not sharing the expected output:
It should be [44.64,-123.11;43.21,-123.36;41.77,-122.58;40.35,-122.28;38.91,-121.99;37.77,-122.42]
li = [44.64,-123.11;38.91,-121.99;40.35,-122.28;43.21,-123.36;41.77,-122.58;37.77,-122.42]
Your "list" looks more like a string, with ";" and "," to separate 2D points and their values. I imagine that you want a list of tuples, that represent the x and y coordinates? So first you need to split your string into a list
li = li.split(';')
Now you have a list of strings, that you need to split into pairs of float values. You can do that with two list comprehensions
li = [(float(a.split(',')[0]), float(a.split(',')[1])) for a in li]
Now you have a list of coordinates that you could sort in some way. Maybe smallest x first or something. Use Python's sorted build-in function to do that, e.g.
sorted_li = sorted(li, key=lambda x: x[0])
The docs are here, read them.
https://docs.python.org/3.6/library/functions.html#sorted

Most Pythonic Way to Select Particular Tuple from List of Tuples

Suppose I have a list of tuples: pairs = [(4,5),(2,6),(6,9),(8,7),(1,1)].
And I have a function def m(pair): return pair[0]**2 + pair[1]**2.
I seek to find the element of pairs for which m returns the greatest output. Specifically, I want to do this as pythonically as possible.
It is clear to me that I could do this with a loop through pairs and a variable to store the maximum-yielding pair seen, but that feels inelegant. I feel as if this should be done with a list comprehension. It is also clear that I could find the pair I want by declaring temp = [m(p) for p in pairs] and then selecting pairs[temp.index(max(temp))], but I'd prefer not to create another list as long as the list of pairs -- again, this feels inelegant.
Looking for pythonic suggestions.
The most Pythonic approach:
result = max(pairs, key=m)
Couldn't you do
max([m(p) for p in pairs])

Categories

Resources