我有两个清单:
frame = ["mercury", "noir", "silver", "white" ]
seat_colors = [
"coconut white", "yello", "black", "green", "cappuccino",
"orange", "chrome", "noir", "purple", "pink", "red",
"matte", "gray", "bermuda blue"
]
Run Code Online (Sandbox Code Playgroud)
我正在尝试将它们组合到一个列表中,其中每个帧都与每个座位颜色唯一匹配.
我想这样使用zip():
In [3]: zip(frame, colors)
Out[3]:
[('mercury', 'coconut white'),
('noir', 'yello'),
('silver', 'black'),
('white', 'green')]
Run Code Online (Sandbox Code Playgroud)
但它会截断到最小列表的长度.
我知道我可以通过以下方式遍历列表:
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
....
Run Code Online (Sandbox Code Playgroud)
但我希望它更聪明,并使用python内置函数的强大功能.
Mar*_*ers 11
使用itertools.izip_longest()保持荏苒,直到最长序列已经用完.
这使用默认值(默认为None)代表较短列表的缺失值.
但是,您的输出正在创建两个列表的产品 ; 使用itertools.product()为:
from itertools import product
for a_frame, color in product(frame, seat_colors):
print '{}, {}'.format(a_frame, color)
Run Code Online (Sandbox Code Playgroud)
这两个概念完全不同.该izip_longest()方法将生产len(seat_colors)物品,而产品则生产len(seat_colors) * len(frame)物品.