簡體   English   中英

使用 2 個不同大小的列表來制作字典 python 中的鍵、值

[英]using 2 different size lists to make key, values in a dict python

我面臨的挑戰是試圖弄清楚如何將 2 個列表用於 dict,其中一個列表的項目少於另一個。 對於列表“名稱”中的每個項目,我想將該項目添加為“組合”字典中的鍵,同時還將“答案”列表中的一個項目添加為鍵的值..但一旦較小列表到達它的結尾添加值我想從頭開始重新開始,直到每個鍵都有一個值。

我很難用谷歌搜索答案,因為我真的不知道如何准確地描述我的問題。

我希望下面的“所需輸出”有助於詳細說明我正在嘗試完成的工作,並感謝任何幫助。

names = ["one", "two", "three"]
answers = ["yes", "no"]

combos = {}

def do_something():
    #do stuff
    print(combos)

do_something()

所需的 output: {"one": "yes", "two": "no", "three": "yes"}

itertools.cycle()正是為了應對這種挑戰:

from itertools import cycle

names = ["one", "two", "three"]
answers = ["yes", "no"]

combos = dict(zip(names, cycle(answers)))

print(combos)
# {'one': 'yes', 'two': 'no', 'three': 'yes'}

給定一個像列表這樣的可迭代對象,它將繼續按順序生成值。 由於zip()在最后一個迭代用完時停止,因此當names沒有剩余時它停止產生值。

您可以使用itertools.cycle

names = ["one", "two", "three"]
answers = ["yes", "no"]


from itertools import cycle
d = dict(zip(names, cycle(answers)))

Output:

{'one': 'yes', 'two': 'no', 'three': 'yes'}

模數 (%) function 非常適合重復列表

names = ["one", "two", "three"]
answers = ["yes", "no"]

combos = {}


def do_something():
    for i, _ in enumerate(names):
        combos[names[i]] = answers[i % len(answers)]
    print(combos)


do_something()

嘗試使用字典理解

result = {name: answers[i % len(answers)] for i,name in enumerate(names)}

暫無
暫無

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

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