假設我有三個這樣的串列:
list_of_lists = [ [1,2,3], [4,5,6], [7,8,9]]
并且不是通常將它們連接起來,我想將它們夾在中間,就好像它們是三疊不同的賓果球一樣,我想從每一疊中依次取出一個球。
而不是得到 [1,2,3,4,5,6,7,8,9] 的串列,我想以一個看起來更像這樣的串列結束:
夾心串列 = [1,4,7,2,5,8,3,6,9]
簡單的邏輯是從每個串列中取出第一個數字,將其附加到一個新串列中,然后從舊串列中洗掉該數字并在串列串列中迭代重復。這會正常作業,但速度非常慢。
還有其他選擇嗎?
uj5u.com熱心網友回復:
當串列長度相等時,這是一個 zip-splat 串列理解:
>>> [n for splat in zip(*list_of_lists) for n in splat]
[1, 4, 7, 2, 5, 8, 3, 6, 9]
如果您需要處理不等長的名單,什么你描述基本上是輪轉配方和itertools檔案中顯示。
uj5u.com熱心網友回復:
使用 zip 按串列中的索引分組。
list_of_lists = [ [1,2,3], [4,5,6], [7,8,9] ]
grouped = list(zip(*list_of_lists))
# [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
然后壓扁它。
import functools
import operator
functools.reduce(operator.iconcat, grouped, [])
# [1, 4, 7, 2, 5, 8, 3, 6, 9]
有關展平串列的更多方法 - 查看此答案
uj5u.com熱心網友回復:
您可以使用 numpy:
sandwiched_list = np.array(list_of_lists).flatten('F').tolist()
#[1, 4, 7, 2, 5, 8, 3, 6, 9]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/369953.html
