Python: zip two lists together without truncation

后端 未结 2 698
花落未央
花落未央 2020-12-06 21:09

I have two lists:

frame = [\"mercury\", \"noir\", \"silver\", \"white\" ] 
seat_colors = [ 
            \"coconut white\", \"yello\", \"black\", \"green\",          


        
相关标签:
2条回答
  • 2020-12-06 21:50

    Use itertools.izip_longest() to keep zipping until the longest sequence has been exhausted.

    This uses a default value (defaulting to None) to stand in for the missing values of the shorter list.

    However, your output is creating the product of two lists; use itertools.product() for that:

    from itertools import product
    
    for a_frame, color in product(frame, seat_colors):
        print '{}, {}'.format(a_frame, color)
    

    The two concepts are quite different. The izip_longest() approach will produce len(seat_colors) items, while the product produces len(seat_colors) * len(frame) items instead.

    0 讨论(0)
  • 2020-12-06 22:10

    You can use itertools.product:

    import itertools
    for item in itertools.product(frame, seat_colors):
        print item
    

    This produces the same results as your nested for loops.

    0 讨论(0)
提交回复
热议问题