gpt4 book ai didi

python - 在 Python 中根据计数器排序,根据频率重新组织

转载 作者:行者123 更新时间:2023-12-01 02:35:46 33 4
gpt4 key购买 nike

我的代码如下所示:

with open('toy_two.json', 'rb') as inpt:

dict_hash_gas = list()
for line in inpt:
resource = json.loads(line)
dict_hash_gas.append({resource['first']:resource['second']})

# Count up the values
counts = collections.Counter(v for d in dict_hash_gas for v in d.values())

# Apply a threshold
counts = {k:v for k,v in counts.iteritems() if v > 1}

print(counts)

数据如下:

{"first":"A","second":"1","third":"2"} 
{"first":"B","second":"1","third":"2"}
{"first":"C","second":"2","third":"2"}
{"first":"D","second":"3","third":"2"}
{"first":"E","second":"3","third":"2"}
{"first":"F","second":"3","third":"2"}
{"first":"G","second":"3","third":"2"}
{"first":"H","second":"4","third":"2"}
{"first":"I","second":"4","third":"2"}
{"first":"J","second":"0","third":"2"}
{"first":"K","second":"0","third":"2"}
{"first":"L","second":"0","third":"2"}
{"first":"M","second":"0","third":"2"}
{"first":"N","second":"0","third":"2"}

对应的输出:

{u'1': 2, u'0': 5, u'3': 4, u'4': 2}

我想做的是对此输出进行排序,以便将其呈现为:

{ u'0': 5, u'3': 4, u'4': 2, u'1': 2}

到目前为止,我尝试了 counts = counts.most_common(),但没有成功。我收到以下错误:

AttributeError: 'dict' object has no attribute 'most_common'

最佳答案

# Count up the values
counts = collections.Counter(v for d in dict_hash_gas for v in d.values())

计数是 Counter实例,它理解 most_common方法。

# Apply a threshold
counts = {k:v for k,v in counts.iteritems() if v > 1}

counts 现在是一个 dict,它无法理解 most_common

您只需先应用 most_common,然后应用阈值:

data = [{"first":"A","second":"1","third":"2"} ,
{"first":"B","second":"1","third":"2"} ,
{"first":"C","second":"2","third":"2"} ,
{"first":"D","second":"3","third":"2"} ,
{"first":"E","second":"3","third":"2"} ,
{"first":"F","second":"3","third":"2"} ,
{"first":"G","second":"3","third":"2"} ,
{"first":"H","second":"4","third":"2"} ,
{"first":"I","second":"4","third":"2"} ,
{"first":"J","second":"0","third":"2"} ,
{"first":"K","second":"0","third":"2"} ,
{"first":"L","second":"0","third":"2"} ,
{"first":"M","second":"0","third":"2"} ,
{"first":"N","second":"0","third":"2"}]

from collections import Counter
c = Counter(int(d["second"]) for d in data)
print(c)
# Counter({0: 5, 3: 4, 1: 2, 4: 2, 2: 1})
print(c.most_common())
# [(0, 5), (3, 4), (1, 2), (4, 2), (2, 1)]
print([(value, count) for value, count in c.most_common() if count > 1])
# [(0, 5), (3, 4), (1, 2), (4, 2)]

关于python - 在 Python 中根据计数器排序,根据频率重新组织,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46258723/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com