簡體   English   中英

合並兩個列表以制作具有相同鍵 Python 的字典

[英]Merge two lists to make dictionary with same key Python

我想知道如何將此代碼更改為不使用 zip 函數。 我還沒有學過這個功能,所以我想知道是否有替代方法來檢索我需要的輸出?

list_one = ['a', 'a', 'c', 'd']
list_two = [1, 2, 3, 4]

dict_1 = {}

for key, value in zip(list_one, list_two):
    if key not in dict_1:
        dict_1[key] = [value]
    else:
        dict_1[key].append(value)

print(dict_1)

我希望輸出是:

{'a': [1, 2], 'd': [4], 'c': [3]}

一個簡單的方法來做到這一點:

l1 = ['a', 'a', 'c', 'd']

l2 = [1, 2, 3, 4]

# Dict comprehension to initialize keys: list pairs
dct = {x: [] for x in l1}

# Append value related to key
for i in range(len(l1)):
    dct[l1[i]].append(l2[i])

print(dct)

輸出:

{'a': [1, 2], 'c': [3], 'd': [4]}

zip()使並行迭代多個列表變得容易。 如果您嘗試理解zip()則很容易復制它。 因此,請在此處官方文檔中找到解釋和示例。

下面是一個帶有實現的示例代碼,

list_one = ['a', 'a', 'c', 'd']
list_two = [1,2,3,4]

dict_1={}
for index in range(len(list_one)):
    if list_one[index] not in dict_1:
        dict_1[list_one[index]]=[list_two[index]]
    else:
        dict_1[list_one[index]].append(list_two[index])
print(dict_1)

輸出:

{'a': [1, 2], 'c': [3], 'd': [4]}

您可以在沒有任何庫的情況下像這樣重寫。

list_one = ['a', 'a', 'c', 'd']
list_two = [1,2,3,4]
dict_1={}
if len(list_one) == len(list_two):
    for i in range(len(list_one)):
        if list_one[i] not in dict_1:
            dict_1[list_one[i]]=[list_two[i]]
        else:
            dict_1[list_one[i]].append(list_two[i])
print(dict_1)

假設兩個列表的長度始終相同,您可以通過遍歷索引來繞過zip()的使用:

dict_1 = {}

for i in range(len(list_one)):
    key = list_one[i]
    value = list_two[i]

    if key not in dict_1:
        dict_1[key] = [value]
    else:
        dict_1[key].append(value)
        
print(dict_1)

正如其他人所說,這不是推薦的方法,因為使用zip()的代碼更具可讀性,而zip()是一個內置函數,所以沒有任何理由不使用它。

暫無
暫無

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

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