python - 如何在 Python 中将 dict 元素值作为列表

标签 python python-3.x python-2.7 list dictionary

我有一个列表。假设 [3,4,2,3,4,2,1,4,5]

我需要根据元素的索引创建字典。

在这种情况下,我需要创建一个字典,如下所示:

{
   '3':[0,3],
   '4':[1,4,7],
   '2':[2,5],
   '1':[6],
   '5':[8]
}

其中元素值是所提供列表中键的索引。

我试过了。但是只能将值更改为整数。但无法将它们制成列表。

有没有办法只用 1 个 for 循环来做到这一点?

我试过的代码:

d=dict()
ll=[1,2,1,2,1,2,3,4,5,5,4,2,4,6,5,6,78,3,2,4,5,7,8,9,4,4,2,2,34,5,6,3]
for i,j in enumerate(ll):
    d[j].append(i)
print(d)

最佳答案

您可以使用 collections.defaultdictenumerate对于 O(n) 解决方案:

from collections import defaultdict

d = defaultdict(list)

A = [3,4,2,3,4,2,1,4,5]

for idx, val in enumerate(A):
    d[val].append(idx)

print(d)

defaultdict(list, {1: [6], 2: [2, 5], 3: [0, 3], 4: [1, 4, 7], 5: [8]})

关于python - 如何在 Python 中将 dict 元素值作为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51898026/

相关文章:

python - 为多个数据库设置一个 MySQLdb 连接对象

Python 使用 matplotlib 在 x 轴上显示特定值

python - 使用 aiohttp.ClientSession() 发出请求时如何为 aiohttp.client 设置日志记录?

python - PRAW Subreddit 模型对于一些请求工作正常 - 然后只发送一段时间 503 错误

python-2.7 - pandas:两个系列之间的差异返回 None

python - 如何在Python中使用正则表达式搜索特定单词?

python-2.7 - 如何在 TensorFlow 中提供自定义梯度

python - 将 Django 的 Python 2.7 升级到 3.x

python - 获取字符串以列值开头的所有行

python - 如何更改 python 3 pandas.DataFrame 的表形式?