我有以下變數:
a = [1, 2, 3]
b = "de" # <-- not a (usual) list !
c = 5 # <-- not a list !
d = [4, 5, 23, 11, 5]
e = ["dg", "kuku"]
現在我想將所有內容a, b, c, d, e連接到一個串列中:
[1, 2, 3, "de", 5, 4, 5, 23, 11, 5, "dg", "kuku"]
我試過itertools.chain了,但沒有用。請告訴我如何進行連接?
uj5u.com熱心網友回復:
chain適用于迭代。你的意思是:連接這些串列和原始值。
我看到兩個步驟:
def ensure_list(x):
if isinstance(x, list):
return x
return [x]
lists = map(ensure_list, (a, b, c, d, e))
concatenated = list(itertools.chain.from_iterable(lists))
uj5u.com熱心網友回復:
您可以定義一個函式,該函式接受任意數量的引數,并根據它們的型別迭代地構造一個串列,如下所示:
a = [1, 2, 3]
b = "de" # <-- not a (usual) list !
c = 5 # <-- not a list !
d = [4, 5, 23, 11, 5]
e = ["dg", "kuku"]
def concat(*args):
out = []
for arg in args:
if isinstance(arg, list):
out.extend(arg)
else:
out.append(arg)
return out
print(concat(a,b,c,d,e))
輸出:
[1, 2, 3, 'de', 5, 4, 5, 23, 11, 5, 'dg', 'kuku']
或者,您可以映射 args 串列,確保它們都是一個串列,然后itertools.chain像這樣組合 map 物件:
def concat(*args):
return list(itertools.chain(*map(lambda x : x if isinstance(x, list) else [x], args)))
print(concat(a,b,c,d,e))
輸出:
[1, 2, 3, 'de', 5, 4, 5, 23, 11, 5, 'dg', 'kuku']
這是一種更不透明的方式來完成相同的事情,只是為了在串列理解中獲得樂趣:
def concat(*args):
return [x
for arg in args
for x in (arg if isinstance(arg, list) else [arg])]
print(concat(a,b,c,d,e))
輸出:
[1, 2, 3, 'de', 5, 4, 5, 23, 11, 5, 'dg', 'kuku']
uj5u.com熱心網友回復:
您必須合并append(),extend()因為您的示例之一不是list( band c) 而是單個整數。
#!/usr/bin/env python3
a = [1, 2, 3]
b = "de"
c = 5
d = [4, 5, 23, 11, 5]
e = ["dg", "kuku"]
the_input = [a, b, c, d, e]
result = []
for element in the_input:
if isinstance(element, list):
result.extend(element)
else:
result.append(element)
print(result)
我不知道有任何類似鏈的方法來改進該示例。
uj5u.com熱心網友回復:
如果您的所有變數都是串列,您可以使用
concat = [*a, *b, *c, *d, *e]
“*”將“解包”串列。
編輯:
如果某些變數不是串列
concat = []
for variable in (a, b, c, d, e):
# check if the variable is iterable (is a list, set, dict, ...)
if __hasattr__(variable, "__iter__"):
concat.extend(variable)
else:
concat.append(variable)
uj5u.com熱心網友回復:
我不建議這樣做,但如果您喜歡串列推導式或單行,這是另一種方法:
to_concat = [a, b, c]
concatenated_list = []
concatenated_list = [item for sublist in [[list_or_val] if not isinstance(list_or_val, list) else list_or_val for list_or_val in to_concat] for item in sublist]
輸出a, b, c = "de", [1, 2], ["dg", "kuku"]:
In [6]: concatenated_list
Out[6]: ['de', 1, 2, 'dg', 'kuku']
它是如何作業的?
這部分:
[[list_or_val] if not isinstance(list_or_val, list) else list_or_val for list_or_val in to_concat]
串列推導式通過將非串列值(如a我們的例子)轉換為串列(因此"de"變為["de"])來創建一個新串列。讓我們稱之為list_of_lists。我們現在想要展平list_of_lists以獲得最終結果,我們可以通過串列推導的另一部分來做到這一點:
[item for sublist in list_of_lists for item in sublist]
(如果您有興趣,請在此處了解有關扁平化的更多資訊)
正如我所說,我不會推薦這個解決方案。理解起來很混亂,而且它的性能可能很糟糕,所以它不適合更大的作業負載。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/478288.html
