All possible variants of zip in Python

前端 未结 4 641
渐次进展
渐次进展 2021-02-06 23:14

For example, I have a code looks like this:

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

How can I get something like this:

[(1,4), (1,5), (2,4), (2,5         


        
4条回答
  •  北荒
    北荒 (楼主)
    2021-02-07 00:11

    Don't overlook the obvious:

    out = []
    for a in [1, 2]:
        for b in [4, 5]:
            out.append((a, b))
    

    or list comprehensions:

    a = [1, 2]
    b = [4, 5]
    out = [(x, y) for x in a for y in b]
    

    Both produce out == [(1, 4), (1, 5), (2, 4), (2, 5)]

提交回复
热议问题