python - 连接两个不同长度的列表中的元素
问题描述
(我确信这已经在某个地方得到了回答,但我真的找不到正确的问题。也许我不知道这个练习的正确动词?)
我有两个清单:
prefix = ['A', 'B', 'C']
suffix = ['a', 'b']
我想得到这个:
output = ['A a', 'A b', 'B a', 'B b', 'C a', 'C b']
我知道该zip
方法,它在加入的列表中以最短的长度停止:
output_wrong = [p+' '+s for p,s in zip(prefix,suffix)]
那么最Pythonic的方式是什么?
编辑:
虽然大多数答案更喜欢itertools.product
,但我更喜欢这个:
output = [i + ' ' + j for i in prefix for j in suffix]
因为它没有引入新的包,但是该包是基本的(好吧,我不知道哪种方式更快,这可能是个人喜好问题)。
解决方案
使用列表理解
prefix = ['A', 'B', 'C']
suffix = ['a', 'b']
result = [val+" "+val2 for val in prefix for val2 in suffix ]
print(result)
输出
['A a', 'A b', 'B a', 'B b', 'C a', 'C b']
推荐阅读
- java - 使用通过jtable从mysql获取多个数据
- entity-framework-core - 用于 cosmos 查询的不区分大小写的 ORDER BY
- javascript - CODEIGNITER4:如何将值从 table_1 链接到我使用 SELECT OPTION 标记插入的 table_2
- reactjs - 调用同级函数和作用域
- github - 我无法将我的文件夹和文件上传到我在 GitHub 上的存储库
- javascript - 画布将元素对齐到网格
- mobile-safari - Adobe TypeKit webfoot 未在 iOS Safari 上显示
- delphi - Delphi7:无法从记录中加载JPEG,但可以直接从数据库中加载
- haproxy - 基于响应头的HAproxy平衡
- kubernetes - 从原始 k8s 清单切换到 helm 图表