首页 > 解决方案 > 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])

还有其他更好的解决方案吗?

标签: python

解决方案


您可以为此使用 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_longestitertools 模块。None对于较短的列表,它将产生类似的结果,填充值(默认值为)。


推荐阅读