Python list and dictionary comprehension

烂漫一生 提交于 2021-02-10 12:52:09

问题


I am trying to get use to list dictionaries comprehension. Here a small code I have not been able to transform.

lst = ['C', 'A', 'B', 'A']
myd = {}
for v, k in enumerate(lst):
    if k in myd:
        myd[k].append(v)
    else:
        myd[k] = [v]

print(myd)

>>> {'C': [0], 'A': [1, 3], 'B': [2]}

I would be please to have some help.


回答1:


Here is the answer, although I think the non comprehension approach is much easier to understand. And as mentioned this is not efficient in the least.

I would stay with what you have.

{k:[i for i, j in enumerate(lst) if j == k] for k in set(lst)}



回答2:


A hack with a helper dict, but at least it's linear time.

>>> {k: d.setdefault(k, []).append(i) or d[k]
     for d in [{}]
     for i, k in enumerate(lst)}
{'C': [0], 'A': [1, 3], 'B': [2]}

A variation:

>>> {k: d.setdefault(k, [i])
     for d in [{}]
     for i, k in enumerate(lst)
     if k not in d or d[k].append(i)}
{'C': [0], 'A': [1, 3], 'B': [2]}


来源:https://stackoverflow.com/questions/65079914/python-list-and-dictionary-comprehension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!