Nested list comprehension with two lists

后端 未结 5 896
误落风尘
误落风尘 2020-12-08 06:09

I understand how the simple list comprehension works eg.:

[x*2 for x in range(5)] # returns [0,2,4,6,8]

and also I understand how the nested

5条回答
  •  粉色の甜心
    2020-12-08 06:58

    List comprehensions are equivalent to for-loops. Therefore, [x + y for x in l2 for y in l1 ] would become:

    new_list = []
    for x in l2:
        for y in l1:
            new_list.append(x + y)
    

    Whereas zip returns tuples containing one element from each list. Therefore [x + y for x,y in zip(l1,l2)] is equivalent to:

    new_list = []
    assert len(l1) == len(l2)
    for index in xrange(len(l1)):
        new_list.append(l1[index] + l2[index])
    

提交回复
热议问题