考虑这些嵌套列表:
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/