初始化di的最具python风格的方法

2024-04-24 03:16:36 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个这样的口授

d = {
    1: [1,4,7],
    2: [2,5,8],
    0: [3,6,9]       
}

它可以由

d = {}

for i in range(1,10):
    key = i % 3
    if key not in d: d[key] = []
    d[key].append(i)

我使用这行if key not in d: d[key] = []来检查dict中是否存在键/值对,并初始化该对。你知道吗

有没有一个更能达到这个目的的方法?你知道吗


Tags: 方法keyin目的forifnotrange
3条回答

最好使用^{}来处理这个问题,如果键值映射还不存在,它将自动创建任何被访问的键值映射。将可调用的函数传递给defaultdict构造函数,该构造函数将用于初始化值。例如:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d
defaultdict(list, {})
>>> d[3]
[]
>>> d
defaultdict(list, {3: []})

使用理解:

>>> {n%3: list(range(n, n+7, 3)) for n in range(1,4)}
{0: [3, 6, 9], 1: [1, 4, 7], 2: [2, 5, 8]}

使用dict.setdefault()

>>> d = {}
>>> for i in range(1, 10):
...     d.setdefault(i%3, []).append(i)
... 
>>> d
{0: [3, 6, 9], 1: [1, 4, 7], 2: [2, 5, 8]}

使用defaultdict

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for i in range(1, 10):
...     d[i%3].append(i)
... 
>>> d
defaultdict(<class 'list'>, {0: [3, 6, 9], 1: [1, 4, 7], 2: [2, 5, 8]})
from collections import defaultdict

d = defaultdict(list)
for i in range(1,10):
    key = i % 3
    d[key].append(i)
print(d)

输出:

defaultdict(<class 'list'>, {0: [3, 6, 9], 1: [1, 4, 7], 2: [2, 5, 8]})

When each key is encountered for the first time, it is not already in the mapping; so an entry is automatically created using the default_factory function which returns an empty list. The list.append() operation then attaches the value to the new list. When keys are encountered again, the look-up proceeds normally (returning the list for that key) and the list.append() operation adds another value to the list. This technique is simpler and faster than an equivalent technique using dict.setdefault():

>>> d = {}
>>> for k, v in s:  
        d.setdefault(k, []).append(v)

相关问题 更多 >