小编Nic*_*olò的帖子

如何加入用for循环创建的词典?

我是Python的新手.

我创建了一个代码,可以让我找到列表中给定项目后面的项目百分比.

给出一个清单:

list1=["a", "b", "a", "c", "a", "b", "c", "d", "e", "a", "b", "d", "e", "a", "c"]
Run Code Online (Sandbox Code Playgroud)

我想为每个人找一个"a",其中每个项目的百分比都在跟随.代码返回:

[(33, 'a'), (25, 'b'), (16, 'e'), (16, 'd'), (16, 'c')]
[(30, 'a'), (20, 'e'), (20, 'd'), (20, 'c'), (20, 'b')]
[(25, 'e'), (25, 'd'), (25, 'b'), (25, 'a'), (12, 'c')]
[(33, 'e'), (33, 'd'), (33, 'b'), (33, 'a')]
[]  
Run Code Online (Sandbox Code Playgroud)

输出是正确的,这就是我想要的.
但我还想总结不同词典的每一个关键词,所以我可以得到类似的东西:

[(121, 'a'), (103, 'b'), (94, 'e'), (94, 'd'), (48, 'c')]
Run Code Online (Sandbox Code Playgroud)

我没有办法做到这一点.我知道有一些方法可以对不同字典中每个键的值进行求和,但问题是字典是在for循环中创建的,因为我需要尽可能多的目标项目(在本例中为"a") .

我尝试用每个字典迭代

   for key, value in dictio.items():
        dictio[key]=value + …
Run Code Online (Sandbox Code Playgroud)

python iteration dictionary loops list

-3
推荐指数
1
解决办法
601
查看次数

标签 统计

dictionary ×1

iteration ×1

list ×1

loops ×1

python ×1