python - 如何根据索引组合嵌套列表?

标签 python python-2.7

考虑这些嵌套列表:

L1 = [[1,2,3],[4,5,6],[7,8,9]]
L2 = [[11,22,33],[44,55,66]]
L3 = [[111,222,333],[444,555,666],[777,888,999]]
L4 = [12,13,14] # Note: not a nested list

我需要:

output1 = [1,4,7,11,44,111,444,777,12]
output2 = [2,5,8,22,55,222,555,888,13]
output3 = [3,6,9,33,66,333,666,999,14]

最佳答案

一条线:

output1, output2, output3 = [[l[i] for l in L1+L2+L3+[L4]] for i in range(3)]

输出:

>>> output1
[1, 4, 7, 11, 44, 111, 444, 777, 12]
>>> output2
[2, 5, 8, 22, 55, 222, 555, 888, 13]
>>> output3
[3, 6, 9, 33, 66, 333, 666, 999, 14]

尽管在寻求解决方案时您确实应该提供您尝试过的示例 :-)

更新

由于我们显然是在进行一场友好的比赛,所以在我的机器 (python3) 上出现不同答案的时间如下:

代码:

import time

L1 = [[1,2,3],[4,5,6],[7,8,9]]
L2 = [[11,22,33],[44,55,66]]
L3 = [[111,222,333],[444,555,666],[777,888,999]]
L4 = [12,13,14]


t = time.process_time()

output1, output2, output3 = [[l[i] for l in L1+L2+L3+[L4]] for i in range(3)]

print(output1)
print(output2)
print(output3)

print("%.7f" %(time.process_time() - t))


t = time.process_time()

output1, output2, output3 = map(list,(zip(*L1+L2+L3+[L4])))

print(output1)
print(output2)
print(output3)

print("%.7f" %(time.process_time() - t))


t = time.process_time()

from itertools import chain

output_1, output_2, output_3 = zip(*chain(L1, L2, L3, [L4]))

print(output1)
print(output2)
print(output3)

print("%.7f" %(time.process_time() - t))

结果(最快的运行之一):

[1, 4, 7, 11, 44, 111, 444, 777, 12]
[2, 5, 8, 22, 55, 222, 555, 888, 13]
[3, 6, 9, 33, 66, 333, 666, 999, 14]
0.0000650
[1, 4, 7, 11, 44, 111, 444, 777, 12]
[2, 5, 8, 22, 55, 222, 555, 888, 13]
[3, 6, 9, 33, 66, 333, 666, 999, 14]
0.0000356
[1, 4, 7, 11, 44, 111, 444, 777, 12]
[2, 5, 8, 22, 55, 222, 555, 888, 13]
[3, 6, 9, 33, 66, 333, 666, 999, 14]
0.0002259

@Chris_Rands 的回答似乎是最快的:-)

关于python - 如何根据索引组合嵌套列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40677843/

相关文章:

Python Websocket - 具有时间和消息限制

python - 删除超过特定深度的所有子标签

python - 如果安装了 ipython,如何在运行 python 时使 ipython 默认?

python - 如何查找连续重复 3 次的列表的重复项

python - 使用 seaborn 绘图时如何处理缺失值?

python-2.7 - 在 python matplotlib 中用多种颜色填充多边形

python - pickle 如何创建一个实例来无视构造函数?

python - 3维字典

python-2.7 - 复杂图像中的角点检测

python - 我已经在计算机上创建了数据库文件,为什么下面没有创建我的表?