All possible variants of zip in Python

前端 未结 4 644
渐次进展
渐次进展 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:00

    You can do this nicely with list comprehension, or better yet with a generator expression if you just need to iterate through the combinations.

    Here's it is using list comprehension:

    a = [1, 2]
    b = [4, 5]
    
    [(i, j) for i in a for j in b]
    

    And here with a generator expression:

    for pair in ((i, j) for i in a for j in b):
        print(pair)
    

提交回复
热议问题