将重复项列表转换成简洁的字典

时间:2019-02-06 15:40:27

标签: python list dictionary

我有列表

a l e x

0 1 2 3


a a l e e x

0 1 2 3 4 5

i 0 = j 0

i 1 = j 2

i 2 = j 3

i 3 = j 5

我想将其转换成这样表示的字典

dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

然后,我想将其与现有字典合并以合并清单。这可能吗?

2 个答案:

答案 0 :(得分:2)

使用“收藏夹”模块中的Counter进行

from collections import Counter
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
dic = Counter(dragonLoot)

答案 1 :(得分:0)

您还可以按如下方式使用理解字典语法:

dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
res = {el: dragonLoot.count(el) for el in  dragonLoot}
print(res)

夹心打印:

{'gold coin': 3, 'ruby': 1, 'dagger': 1}