I have a nested list in python, i=[[1,2,3],[4,5,6]]. I want to sum the terms such that the final result is j=[1+4,2+5,6+3]. I have tried:
i=[[1,2,3],[4,5,6]]
j=[sum(x) for x in zip(i)]
But this is what I get instead:
>>>print j
[6, 15]
zip does not take a list of lists as an argument. It takes an arbitrary long list of list arguments.
Here is how to do it:
i=[[1,2,3],[4,5,6]]
j=[sum(x) for x in zip(*i)]
You forgot the *
>>> i=[[1,2,3],[4,5,6]]
>>> [sum(x) for x in zip(*i)]
[5, 7, 9]
Related
Hello I have a few lists and im trying to create a new list of the highest values repsectively. for an example, these are the lists:
list1 = 5, 1, 4, 3
list2 = 3, 4, 2, 1
list3 = 10, 2, 5, 4
this is what I would like it to return:
[10, 4, 5, 4]
I thought that I could do a something like this:
largest = list(map(max(list1, list2, list3)))
but I get an error that map requires more than 1 argument.
I also thought I could write if, elif statements for greater than but it seems like it only does the first values and returns that list as the "greater value"
thanks for any help
This is the "zip splat" trick:
>>> lists = [list1, list2, list3]
>>> [max(col) for col in zip(*lists)]
[10, 4, 5, 4]
You could also use numpy arrays:
>>> import numpy as np
>>> np.array(lists).max(axis=0)
array([10, 4, 5, 4])
You have used map incorrectly. Replace that last line with this:
largest = list(map(max, zip(list1, list2, list3)))
In map, the first argument is the function to be applied, and the second argument is an iterable which will yield elements to apply the function on. The zip function lets you iterate over multiple iterables at once, returning tuples of corresponding elements. So that's how this code works!
Using map's iterableS argument has an implicit zip-like effects on the iterables.
map(max, *(list1, list2, list3))
I have a Python list like:
mylist = [1,2,3,4,5,6,7,8]
And I want to run an operation on each two consecutive variables. For example I want to sum each two consecutive variables in the list and put them into another list:
newlist = [1+2, 3+4, 5+6, 7+8]
But how can I do that in Python? I didn't know where to start. Should I use two nested for loops, or enumerate, or zip function? I am confused.
My favorite way to do this is with an explicit list_iterator.
itr = iter(mylist)
newlist = [x + y for x, y in zip(itr, itr)]
zip advances the iterator by two elements each time it yields a pair. The benefit of using an iterator over slicing is that it doesn't require you to make two half-copies of the list before zipping.
If you don't like two lines, Python 3.8 can fold the assignment into an expression:
from operator import add
newlist = list(map(add, (i:=iter(mylist)), i))
(For some reason, you can't use an assignment expression in a list comprehension.
[x + y for x, y in zip((i:=iter(mylist)), i)]
is a syntax error, but
t = zip((i:=iter(mylist)), i)
[x + y for x, y in t]
is fine. I suspect it has something to do with scoping, but I don't know the technical details.)
Solution with zip():
out = [a+b for a, b in zip(mylist[::2], mylist[1::2])]
print(out)
Prints:
[3, 7, 11, 15]
The range() function defaults to increment the sequence by 1, but one can increment the value by adding a third parameter - range(start, stop, step_size).
You can try this:-
res = [mylist[i]+mylist[i+1] for i in range(0,len(mylist)-1, 2)]
print(res)
Output:-
[3, 7, 11, 15]
You can use this list comprehension:
mylist = [1,2,3,4,5,6,7,8]
mylist =[n+mylist[i-1] for i,n in enumerate(mylist) if i%2]
print(mylist)
Output:
[3, 7, 11, 15]
I have a spectra of wavelengths as a list and some number of other lists I use in a formula (using tmm.tmm_core). Is there something more efficient than iterating through the wavelength if I'm just basically doing the same thing for all wavelengths?
Example
def go(n, thk, theta):
#do stuff
return(something)
wv = [1, 2, 3, 4]
a_vec = [3, 7, 3, 9]
b_vec = [6, 5, 9, 3]
c_vec = [0, 1, 8, 9]
theta = 0
th = [10, 1, 10]
final = []
for i in range(len(wv)):
n = [a[i], b[i], c[i]]
answer = go(n, th, theta)
final.append(answer)
in reality there are maybe 5000-10000 rows. It just seems to lag a bit when I press go and I assume it's because of the iteration. Pretty new to optimizing so I haven't used any benchmarking tools or anything.
I think you're looking for the map function in Python!
>>> list1 = [1,2,3,4]
>>> list2 = [5,6,7,8]
>>> map(lambda x,y: x+y, list1, list2)
[6, 8, 10, 12]
it takes in a function (in the above case, an anonymous lambda function), one or more lists and returns another list. At each iteration within the function, both lists are iterated and the result is added to the new list. You don't need to limit yourself to the expressive power of a lambda statement; you can also use globally defined functions as in the case below:
>>> def go(a,b,c):
... return a+b+c
...
>>> map(go, list1,list2, range(9,13))
[15, 18, 21, 24]
You can put all of your lists within a custom list like C_list and use map to create a new list all_len contain the length of all lists then use a list comprehension to create the list final :
all_len=map(len,C_list)
final =[[go([a[i], b[i], c[i]], th, theta) for i in range(li)] for li in all_len]
Also if the length of a and b and c are equal you can use zip function to zip then and refuse of multiple indexing :
all_len=map(len,C_list)
z=zip(a,b,c)
final =[[go(z[i], th, theta) for i in range(li)] for li in all_len]
If you have to perform an operation on every item in the list, then you're gonna have to go through every item in the list. However, you could gain speed through the use of list comprehensions: List Comprehensions
I need to find the smallest value in a series of lists. I understand the code for the smallest value in just one list:
>>> x = [1, 2, 3, 4, 5]
>>> print (min(x))
1
Simple enough. However, I would like to know if there is a way to write code that finds the smallest value for each list I have without stopping and adjusting the code (whether by an iterative process or some other means). Any help would be greatly appreciated. Thanks in advance!
First, make a list of lists out of your separate lists. For example, if you have lists A, B and C, the list of lists would be [A,B,C].
Now, to get a list of all the minimum values for each list in a list of lists lst:
[min(x) for x in lst]
To get the global minimum:
min(x for sublist in lst for x in sublist)
Demo:
>>> lst
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [min(x) for x in lst]
[1, 4, 7]
>>> min(x for sublist in lst for x in sublist)
1
Edit in reaction to OP's comment:
I just want the minimum value for each list. I don't need to compile all of the minimum values together into a new list
If you just want to print the minimum values for each list A, B, C, ... , you can do:
for lst in (A,B,C): # put as many lists as you like into the parentheses
print(min(lst))
Edit in reaction to
I am only accessing one list (in this case, the values are well depths) at a time. [..] What I would like to know is how to write a code that finds the smallest value in a list given that the iterator essentially changes the values in said list.
Just print(min(lst)) each time lst has changed.
Assuming you've got a list of lists, this should do it:
minimums = [min(l) for l in lists]
I am trying to merge 2 lists like so
coordinates_X = [1, 17, 9]
coordinates_Y = [3, 5, 24]
outcome = [1, 3, 17, 5, 9, 24]
Are the lists always the same length? If so, this will give you a list of tuples:
outcome = zip(coordinates_X, coordinates_Y)
You can then flatten that:
import itertools
outcome = list(itertools.chain.from_iterable(zip(coordinates_X, coordinates_Y)))
For 2.x, itertools also has izip available, which builds an iterable yielding tuples. But that's unnecessary for lists this small. On 3.x, zip always returns an iterable.
If they're not the same length, zip or itertools.izip will truncate the outcome to match the shorter list. itertools.izip_longest can extend a shorter list with a fill value specified in the call, if you need that.
An alternate without itertools:
result = []
for i in zip(coordinates_X,coordinates_Y):
result.extend(i)
** the Code you can use is: **
coordinates_X = [1, 17, 9]
coordinates_Y = [3, 5, 24]
outcome =coordinates_X+coordinates_Y
If ordering isn't required, you can do:
coordinates_X + coordinates_Y
Also, you can use list comprehensions to output exactly what you
[ x for y in map(lambda x, y: [x, y], coordinates_X, coordinates_Y) for x in y ]
Probably not the best way to do it, but it was what occurred to me :).