开发者

Python traversing two lists

I found this nice statement in a tutorial:

    for x,y in [(x,y) for x in listA for y in listB]:

Now,开发者_高级运维 as for me, I understood, that that statment will traverse listA and listB and x is a value of list A and y is a value from listB. But in this example the two lists had the same length. Will this statement also give me all pairs, if one list is longer than the other, or do I have to use a different statement?

Thanks in advance.


The code computes the cartesian product (itertools.product), not zip as you suggested.

For example, if the inputs are [1,2,3] and [4,5], the result is:

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

For comparison, the result of zip([1,2,3], [4,5]) is:

(1,4)
(2,5)

As you can see, zip (or itertools.izip) discards the additional items in the longer argument.

Its variant itertools.izip_longest replaces these missing elements with an arbitrary value. For example, iterttools.izip_longest([1,2,3], [4,5], 99) returns:

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


The example will produce all combinations of all the items in listA and listB. Think of it as writing

for x in listA:
    for y in listB:
        …


I like to add an answer for Traversing two list same at time.

alist = [1,2,3,4,5]
blist = [6,7,8,9,0]

for a,b in zip(alist,blist):
    print a,"+",b,'=',a+b

it will give output like

1 + 6 = 7
2 + 7 = 9
3 + 8 = 11
4 + 9 = 13
5 + 0 = 5
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜