简体   繁体   中英

Python: zip two lists together without truncation

I have two lists:

frame = ["mercury", "noir", "silver", "white" ] 
seat_colors = [ 
            "coconut white", "yello", "black", "green", "cappuccino", 
            "orange", "chrome", "noir", "purple", "pink", "red", 
            "matte", "gray", "bermuda blue" 
                                            ]

I'm trying to combine them to a single list where every frame is uniquely matched with every seat color.

I'd like to use zip() like so:

In [3]: zip(frame, colors)

Out[3]:
[('mercury', 'coconut white'),
 ('noir', 'yello'),
 ('silver', 'black'),
 ('white', 'green')]

But it truncates to the length of the smallest list.

I know I can iterate through the lists with:

In [5]:

for f in frame:
    for c in colors:
        print "%s, %s" %(f, c)

Out [5]:
mercury, coconut white
mercury, yello
mercury, black
mercury, green
mercury, cappuccino
mercury, orange
mercury, chrome
mercury, noir
mercury, purple
mercury, pink
mercury, red
mercury, matte
mercury, gray
mercury, bermuda blue
noir, coconut white
noir, yello
noir, black
noir, green
....

But I'd like the to be smarter about it and use the power of python's built in functions.

Any ideas how to use zip ( or something like zip ) and avoid truncation?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM