Python:将两个列表压缩在一起而不截断

 变更后2010 发布于 2023-01-31 09:06

我有两个清单:

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

我正在尝试将它们组合到一个列表中,其中每个帧都与每个座位颜色唯一匹配.

我想这样使用zip():

In [3]: zip(frame, colors)

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

但它会截断到最小列表的长度.

我知道我可以通过以下方式遍历列表:

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
....

但我希望它更聪明,并使用python内置函数的强大功能.

任何想法如何使用zip(或类似zip)并避免截断?

Martijn Piet.. 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)

这两个概念完全不同.该izip_longest()方法将生产len(seat_colors)物品,而产品则生产len(seat_colors) * len(frame)物品.

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有