小编bek*_*man的帖子

如何在dicts列表中查找公共密钥并按值对其进行排序?

我想创建一个finalDic,它包含公共键和值的总和

myDic = [{2:1, 3:1, 5:2}, {3:4, 6:4, 2:3}, {2:5, 3:6}, ...]
Run Code Online (Sandbox Code Playgroud)

首先找到共同的密钥

commonkey = [{2:1, 3:1}, {2:3, 3:4}, {2:5, 3:6}]
Run Code Online (Sandbox Code Playgroud)

然后按它们的值求和并排序

finalDic= {3:11, 2,9}
Run Code Online (Sandbox Code Playgroud)

我试过这个,甚至没有关闭我想要的东西

import collections

myDic = [{2:1, 3:1, 5:2}, {3:4, 6:4, 2:3}, {2:5, 3:6}]

def commonKey(x):
    i=0
    allKeys = []
    while i<len(x):
        for key in x[0].keys():
            allKeys.append(key)
        i=i+1
    commonKeys = collections.Counter(allKeys)
    commonKeys = [i for i in commonKeys if commonKeys[i]>len(x)-1]
    return commonKeys

print commonKey(myDic)
Run Code Online (Sandbox Code Playgroud)

谢谢

python sorting dictionary list

4
推荐指数
1
解决办法
1103
查看次数

Python字符串切片

如何切换字符串与我的列表进行比较.

string = "how to dye my brunet hair to blonde? "
list = ['how', 'how to',...]
Run Code Online (Sandbox Code Playgroud)

我希望代码删除"如何"并打印其余部分.

 dye my brunet hair to blonde?
Run Code Online (Sandbox Code Playgroud)

任何的想法?

python string slice

1
推荐指数
1
解决办法
2946
查看次数

标签 统计

python ×2

dictionary ×1

list ×1

slice ×1

sorting ×1

string ×1