首页 > 解决方案 > 使用推导在字典的值字段中附加元素

问题描述

我有一个元素列表,可以说:

y = [1, 3, 1, 5, 1]

我想创建一个字典,其中:

我尝试了以下理解。

a={elem:y[i] for i, elem in enumerate(y[1:])}

但是,由于字典中的value字段不是列表,它只保留最后一次出现key的前一个元素。

换句话说,对于这个例子,我得到以下信息:

{3: 1, 1: 5, 5: 3}

有没有办法使用理解来做到这一点?

注意:我忘记添加所需的结果。

{3: [1], 1: [3,5], 5: [1]}

标签: pythonpython-3.xlist-comprehensiondictionary-comprehension

解决方案


Your keys are duplicated, so you cannot create a dictionary with them (you'll lose the first elements).

So comprehensions are difficult to use (and inefficient, as stated by other comprehension answers here) because of the accumulation effect that you need.

I suggest using collections.defaultdict(list) instead and a good old loop:

import collections

y = [1, 3, 1, 5, 1]

d = collections.defaultdict(list)

for i,x in enumerate(y[1:]):
    d[x].append(y[i])  # i is the index of the previous element in y

print(d)

result:

defaultdict(<class 'list'>, {1: [3, 5], 3: [1], 5: [1]})

推荐阅读