For-loop over several variables from a single list
I'm trying to create a loop开发者_如何学编程 like this
newList = [a + b for a,b in list[::2], list[1::2]]
meaning, take two consecutive entries from a list, do something with them and put the into a new list.
How would that work?
You want to zip
your two newly created lists:
newList = [a + b for a,b in zip(list[::2], list[1::2])]
You also do this in a somewhat more memory-efficient manner by using an iterator:
it = iter(list)
newList = [a + b for a, b in zip(it, it)]
or even more efficiently* by using the izip
function, which returns an iterator:
import itertools
it = iter(list)
newList = [a + b for a, b in itertools.izip(it, it)]
* at least under Python 2.x; in Python 3, as I understand it, zip
itself returns an iterator.
Note that you really should never call a variable list
as this clobbers the builtin list
constructor. This can cause confusing errors and is generally considered bad form.
>>> L=range(6)
>>> from operator import add
>>> map(add, L[::2], L[1::2])
[1, 5, 9]
alternatively you could use an iterator here
>>> L_iter = iter(L)
>>> map(add, L_iter, L_iter)
[1, 5, 9]
since you pass the same iterator twice, map()
will consume two elements for each iteration
Another way to pass the iterator twice is to build a list with a shared reference. That avoids the temporary variable
>>> map(add, *[iter(L)]*2)
[1, 5, 9]
of course you can replace add
with your own function
>>> def myfunc(a,b):
... print "myfunc called with", a, b
... return a+b
...
>>> map(myfunc, *[iter(L)]*2)
myfunc called with 0 1
myfunc called with 2 3
myfunc called with 4 5
[1, 5, 9]
And it's easy to expand to 3 variables or more
>>> def myfunc(*args):
... print "myfunc called with", args
... return sum(args)
...
>>> map(myfunc, *[iter(L)]*3)
myfunc called with (0, 1, 2)
myfunc called with (3, 4, 5)
[3, 12]
Zip and Map come in handy here.
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> list(zip(a, b))
[(1, 4), (2, 5), (3, 6)]
>>> list(map <operation>, (zip(a, b)))
>>> ...
Or in your case,
>>> list(map(lambda n: n[0] + n[1], (zip(a, b))))
[5, 7, 9]
There's definitely a better way to pass the plus operation to the map. Feel free to add to it, anyone!
精彩评论