質問

In Python , as we all know there is a useful function : zip for instance:

a = [1,2,3,4,5]
b = [5,4,3,2,1]

we can "add" these lists in one line:

c = [ x[0] + x[1] for x in zip(a,b) ]

But it seems zip created a new list. In many cases , which I want is just a pair of data( a[i],b[i] ) , I don't want the "zip" list at all.

In c# , we can make a iterator to get pair data from a and b , so we could avoid to make a new "zip" list.

What about python?

役に立ちましたか?

解決

It is itertools.izip():

Make an iterator that aggregates elements from each of the iterables. Like zip() except that it returns an iterator instead of a list. Used for lock-step iteration over several iterables at a time.

Example:

>>> from itertools import izip
>>> a = [1,2,3,4,5]
>>> b = [5,4,3,2,1]
>>> c = izip(a, b)
>>> c
<itertools.izip object at 0x10d1aaf38>
>>> for x, y in c:
...     print x, y
... 
1 5
2 4
3 3
4 2
5 1

Note that in Python-3.x izip() is gone, zip() returns an iterator.

他のヒント

You don't need a function per se, just use a generator expression:

a = [1,2,3,4,5]
b = [5,4,3,2,1]

for pair in ((a[i], b[i]) for i in xrange(min(len(a), len(b)))):
    print pair

Output:

(1, 5)
(2, 4)
(3, 3)
(4, 2)
(5, 1)

Generator for fixed or variable number of iterables

You may create your own generator in Python too:

def mygen(a, b):
    """generator yielding values from two iterables"""
    aiter = iter(a)
    biter = iter(b)
    while True:
        yield aiter.next(), biter.next()

def dyngen(*iterables):
    """generator for yielding list from dynamic number of iterables"""
    iterables = map(iter, iterables)
    while True:
        yield  map(next, iterables)

if __name__ == "__main__":
    a = [1,2,3,4,5]
    b = [5,4,3,2,1]
    c = ["a", "b", "c", "d", "e"]

    gen = mygen(a, b)
    print gen.next()
    print gen.next()
    print gen.next()
    print gen.next()
    print gen.next()

    print "dyngen"
    gen = dyngen(a, b, c)
    print gen.next()
    print gen.next()
    print gen.next()
    print gen.next()
    print gen.next()

Calling from command line:

$ python myzip.py 
(1, 5)
(2, 4)
(3, 3)
(4, 2)
(5, 1)
dyngen
[1, 5, 'a']
[2, 4, 'b']
[3, 3, 'c']
[4, 2, 'd']
[5, 1, 'e']

Try to use map() as below:

c = map(lambda x,y:x+y,a,b)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top