python - python - 在相应列表中获取元组的第 i 个、第 j 个和第 k 个元素
问题描述
我有一个包含数据的元组
results = ((a, b, c, d), (1, 2, 3, 4), (q, w, e, r))
我需要不同列表中的第一个、第二个和第三个元素,例如:
one = [a, 1, q]
two = [b. 2, w]
thr = [c, 3, e]
我这样做是这样的:
one = [r[0] for r in results]
two = [r[1] for r in results]
thr = [r[2] for r in results]
但我觉得有一种方法可以在一行而不是三个循环中做到这一点。
我能想到的其他方式就像
for r in results:
one.append(r[0])
two.append(r[1])
thr.append(r[2])
还有其他更好的解决方案吗?
解决方案
您可以为此使用 zip:
>>> for (one, two, thr) in zip(*results):
... print (one, two, thr)
...
a 1 q
b 2 w
c 3 e
d 4 r
如果您正在处理锯齿状列表并关心较长列表末尾的元素,您应该查看zip_longest
itertools 模块。None
对于较短的列表,它将产生类似的结果,填充值(默认值为)。
推荐阅读
- angular - p-accordionTab 在点击不同的锚标签时打开扭曲的 UI
- php - 文本框数组中的值未更新
- r - R中的chart.Bar()不能获取动物园对象
- javascript - Angular 7 Web 应用程序中的 watsapp 共享
- javascript - 如何保存有关功能的信息以供以后使用?
- java - 从最后一个字符开始并向后迭代 3
- postgresql - 访问 postgreSQL 中的子 json 元素
- php - 如何从另一个逗号分隔列表中获取从 y 开始的 x 项的逗号分隔列表
- android - 在内部类 Kotlin 中获取外部值
- django - for循环在django的单元测试中不起作用?