python - 使用推导在字典的值字段中附加元素
问题描述
我有一个元素列表,可以说:
y = [1, 3, 1, 5, 1]
我想创建一个字典,其中:
- 键:是y中的元素
- Values:是出现在y中的Key之前的元素列表
我尝试了以下理解。
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]}
解决方案
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]})
推荐阅读
- html - 如何使用从 Django 表单中的表单获取的数据?
- html - 如何在容器中获取不同的背景?
- android - 我应该如何处理要求允许或拒绝移动自动化选项的基于摄像头的弹出窗口?
- php - htaccess:如何删除 index.php 之外的 php 扩展?param=
- javascript - Vuejs2打印由换行符分隔的数组元素
- javascript - ckeditor 配置 autolink_urlRegex 不起作用
- crystal-lang - How to rescue/catch an "Error writing file: Broken pipe (Errno)" exception?
- ubuntu-16.04 - 通过连接本地网络上的其他本地计算机,在计算机启动时自动运行脚本
- excel - 使用反向循环删除行 - VB
- linear-regression - 在我的数据集上运行线性回归后,我的 RMSE 即将到来 1109.181