python - 将三个列表合并为 1 个列表
问题描述
嗨,我有三个这样的列表:
a = [1,2,3,4]
b = [2,3,4,5]
c = [3,4,5,6]
如何制作一个新列表,以便从所有列表中获取值。例如,它的前三个元素将是 1、2、3,因为它们是 a、b、c 的第一个元素。因此,它看起来像
d = [1,2,3,2,3,4,3,4,5,4,5,6]
解决方案
您可以使用zip
:
a = [1,2,3,4]
b = [2,3,4,5]
c = [3,4,5,6]
[item for sublist in zip(a, b, c) for item in sublist]
# [1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6]
第一个 for 循环:
for sublist in zip(a, b, c)
将迭代由 提供的元组zip
,这将是:
(1st item of a, 1st item of b, 1st item of c)
(2nd item of a, 2nd item of b, 2nd item of c)
...
第二个 for 循环:
for item in sublist
将迭代这些元组的每一项,构建最终列表:
[1st item of a, 1st item of b, 1st item of c, 2nd item of a, 2nd item of b, 2nd item of c ...]
要回答@bjk116 的评论,请注意理解中的for
循环的编写顺序与您在普通叠层循环中使用的顺序相同:
out = []
for sublist in zip(a, b, c):
for item in sublist:
out.append(item)
print(out)
# [1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6]
推荐阅读
- scrapy - 消除几个同名蜘蛛的 Scrapy 警告
- javascript - 使用 mongoose 查询 mongoDB 中的子文档
- webdriver-io - JUnit 报告器生成空的 xml 文件
- html - 如果句子进入下一行,如何将jquery自动完成定位在单词旁边?
- python - Python3.7 获取两个目录下多个文件的差异
- react-native - 系统重启后 Expo 不启动
- r - 如何使用“for”循环用 ggplot2 绘制点?
- shell - 卷曲循环问题
- java - Java Spring Jpa 嵌入式实体 PropertyNotFoundException 找不到字段名称问题
- c++ - 如何将用户与一本书(图书馆系统)C ++联系起来