簡體   English   中英

將項目添加到列表字典的 Pythonic 方式

[英]Pythonic way of adding items to a dict of lists

我經常使用這個片段:

d = {}
for x in some_list:
    y = some_func(x)  # can be identity 
    if y in d:
        d[y].append(another_func(x))
    else:
        d[y] = [another_func(x)]

這是最pythonic的方法還是有更好的方法? 我使用 Python 3。

你可以試試

from collections import defaultdict

d = defaultdict(list)
for x in some_list:
    d[some_func(x)].append(another_func(x))

defaultdict 是一個字典選項,您可以使用要分配的類型對其進行初始化,以防您要查找的鍵在字典的鍵中不存在。 在這種情況下,每次調用 d 如果鍵不存在,它將創建一個空列表。

暫無
暫無

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

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