簡體   English   中英

如何連接 Python 中的兩個列表?

[英]How can I concatenate two lists in Python?

to_do_list = ["studying", "coding"]

Times = [3, 4] #per hour

我想變成這樣:

["studying", 3, "coding", 4]

Python中有字典,兩個東西相互匹配:

這是您正在尋找的東西,還是您正在嘗試將這兩個列表組合起來自動化 thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict)

串聯是當您將一個列表添加到另一個列表的末尾時:

>>> to_do_list + Times
['studying', 'coding', 3, 4]

但你不想要那個; 你想讓他們交替! zip function 是一個很好的方法:

>>> [t for t in zip(to_do_list, Times)]
[('studying', 3), ('coding', 4)]
>>> [i for t in zip(to_do_list, Times) for i in t]
['studying', 3, 'coding', 4]

查看https://www.geeksforgeeks.org/python-interleave-multiple-lists-of-same-length/ ,它共享以下內容。

# initializing lists  
test_list1 = [1, 4, 5] 
test_list2 = [3, 8, 9] 

# printing original lists 
print ("Original list 1 : " + str(test_list1)) 
print ("Original list 2 : " + str(test_list2)) 

# using list slicing 
# to interleave lists 
res = test_list1 + test_list2 
res[::2] = test_list1 
res[1::2] = test_list2 

# printing result 
print ("The interleaved list is : " + str(res)) 

對於您的程序,您可以這樣做:

>>> to_do_list = ["studying", "coding"]
>>> times=[3,4]
>>> res = to_do_list + times #combine lists
>>> res[::2] = to_do_list #every other element starting at 0
>>> res[1::2] = times #every other element starting at 1
>>> print(res)
['studying', 3, 'coding', 4]

最快的解決方案可能是使用 zip:

list1 = [1,2]
list2 = [3,4]

list(zip(list1,list2))

或者一些列表理解:

[sub_list[i] for i in range(len(list2)) for sub_list in [list1, list2]] 

Output:

[1,3,2,4]

對於其他解決方案: https://www.geeksforgeeks.org/python-merge-two-lists-alternatively/

串聯是當您將一個列表添加到另一個列表的末尾時:

>>> to_do_list + Times
['studying', 'coding', 3, 4]

但你不想要那個; 你想讓他們交替! zip function 是一個很好的方法。 當您將zip兩個列表放在一起時,您會得到一個可迭代的元組,將列表“壓縮”在一起:

>>> [t for t in zip(to_do_list, Times)]
[('studying', 3), ('coding', 4)]

要從這些元組中取出元素並將它們放入一個列表中,請添加另一個理解(即,對於從zip中取出的每個t執行類似for i in t的操作):

>>> [i for t in zip(to_do_list, Times) for i in t]
['studying', 3, 'coding', 4]

可以有多種方法來做到這一點。

如果您要做的任務是'將每個列表中的元素交替放入一個列表',最直觀的方法是使用 for 循環。

假設兩個列表具有相同的長度,

list_1 = [1, 2, 3, 4, 5]
list_2 = ['a', 'b', 'c', 'd', 'e']

list_out = []
for i in range(len(list_1)):
    list_out.append(list_1[i])
    list_out.append(list_2[i])

或者,如果您想更簡單地執行此操作,請嘗試以下操作:

list_out = sum([[a, b] for a, b in zip(list_1, list_2)], [])

(其實上面的代碼可以分成兩行:

zipped = [[a, b] for a, b in zip(list_1, list_2)] # using list comprehension and zip function
# zipped = [[1, 'a'], [2, 'b'], [3, 'c'], [4, 'd'], [5, 'e']]

list_out = sum(zipped, [])  # concatenate all list elements in 'zipped'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM