我有3個不同的列表,我需要合併它們。只需要一個元素或添加一個inteire list來擴展列表就很容易。但是在中間添加更多列表或添加變量時,似乎不可能。擴展:從其他列表(或變量)列表中合併字符串
list1 = [ 'a', 'b', 'c']
list2 = [ 'd', 'e', 'f']
list3 = ['g', 'h', 'i']
添加只是一個列表:
list1.extend(list3)
返回:
['a', 'b', 'c', 'g', 'h', 'i']
添加兩個列表:
list1.extend((list2,list3))
返回兩個名單內的另一個列表:
['a', 'b', 'c', ['d', 'e', 'f'], ['g', 'h', 'i']]
添加兩個列表與運營商 '+':
list1.extend((list2 + list3))
返回
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
,但如果你需要做的是這樣的:
list1.extend(('test' + list2 + fetch[0] + list3 + etc, etc, etc))
不會工作。無法並置。
一個臨時的解決增加了循環可能是:
for l1 in list2:
list1.extend(l1)
for l2 in list3:
list1.extend(l2)
終於有:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
顯然線和週期
浪費是否有存檔更有效的方法沒有使用外部模塊?
編輯:簡單列表的例子只是爲了瞭解基本上我需要什麼。真正的問題是在'.extend'的一行上添加字符串或數字或索引。
解決:
韋恩沃納驅動我到正確的方向來連接不同類型的元件。
list1 = [ 'a', 'b', 'c']
list2 = [ 'd', 'e', 'f']
list3 = ['g', 'h', 'i']
for other_list in (['test'], str(1), list2[2], list2[1]):
list1.extend(other_list)
結果:
['a', 'b', 'c', 'test', '1', 'f', 'e']
您的預期輸出是否等於'list1 + list2 + list3'? –
列表+列表工作正常,直到您需要添加str o int。 –
@ Two-BitAlchemist:no。我意識到(之後)這個例子不是我想要的。我已經更新了我的問題。下一次我會在發送之前再次準備好。當我需要在列表中添加不同類型的元素時,遇到一些麻煩。 –