本文介绍了Python列表和字典理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图用来列出字典理解.这是我无法转换的一小段代码.

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]}

请您帮忙.

推荐答案

这就是答案,尽管我认为非理解方法更容易理解.而且如上所述,这至少是无效的.

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.

我会留着你所拥有的.

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

这篇关于Python列表和字典理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 09:44