[英]Most programmatically elegant (pythonic) way to take ith element of list of lists of lists, and create lists of these ith elements
假設您有一個列表列表,例如
lll = [(['a', 'b'], [1, 2], [True, False]),
(['c'], [3], [True]),
(['d', 'e', 'f', 'g'], [4, 5, 6, 7], [True, False, True, False])]
對於 lll 中的每個項目,我想要每個項目列表中第 i 個元素的列表,並且我希望所有這些列表都在一個列表中。
這很難用你可以想象的文字來描述,但我希望最終的結果是這樣的
result = [
['a', 1, True],
['b', 2, False].
['c', 3, True],
['d', 4, True],
['e', 5, False],
['f', 6, True],
['g', 7, False]
]
到目前為止我嘗試的是
newList = []
for item in lll:
num_things = len(item[0])
for ii in range(num_things):
newList.append([x[ii] for x in item])
newList
有沒有更優雅的方式來獲得這個結果?
result = []
for item in lll:
result.extend(zip(*item))
相當簡潔和 Pythonic,可以說比單行更具可讀性,沒有導入並且值得考慮。 extend
是append
+ loop 用於展平列表的常見重構, zip
幾乎總是 go 用於列迭代和矩陣旋轉的方式。
如果您需要列表而不是元組:
result = []
for item in lll:
result.extend([list(x) for x in zip(*item)])
或使用map
:
for item in lll:
result.extend(map(list, zip(*item)))
由PEP-8提供的一些小風格建議:
snake_case
優於camelCase
。l
作為變量名。 對於i
和1
來說太容易混淆了。 此外, num_things = len(item[0])
讓我覺得有點危險,因為如果item
為空,它會引發IndexError
。
沒有進口的簡單單線:
[[*ys] for xss in lll for ys in zip(*xss)]
zip-star 轉置,第二個for
連接,內部方括號將元組從 zip 轉換為列表。
使用zip
+ chain.from_iterable
from itertools import chain
o = chain.from_iterable(zip(*ll) for ll in lll)
print(list(o))
# output
# [('a', 1, True), ('b', 2, False), ('c', 3, True), ('d', 4, True), ('e', 5, False), ('f', 6, True), ('g', 7, False)]
然后,您可以 map 使用列表理解列出每個元素,因為您想要列表列表而不是元組列表。
l = [list(i) for i in o]
print(l)
# output
# [['a', 1, True], ['b', 2, False], ['c', 3, True], ['d', 4, True], ['e', 5, False], ['f', 6, True], ['g', 7, False]]
我相信你想要這個:
list(map(list,zip(*[sum(l,[]) for l in zip(*lll)])))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.