【发布时间】:2018-07-31 04:07:08
【问题描述】:
所以我试图计算文本文件中重复次数最多的值。通过使用Counter 方法,它准确地返回我正在寻找的内容
文件.txt
12334
99965
99965
44144
99965
00000
44144
script.py
pArray=[]
with open("file.txt") as my_file:
for line in my_file:
pArray.append((line.split('\n'))[0])
dictn = Counter(pArray)
print(dictn)
for key, value in dictn.items():
print("KEY",key)
print("VALUE",value)
print(dictn)
输出
Counter({'99965': 3, '44144': 2, '12334': 1, '00000': 1})
KEY 12334
VALUE 1
KEY 99965
VALUE 3
KEY 44144
VALUE 2
KEY 00000
VALUE 1
['12334', '99965', '44144', '00000']
但是如你所见,最终数组的输出顺序与字典的顺序不同
(value 应该是降序排列)
我期待这样的输出
['99965', '44144', '12334', '00000']
我也试过list(dictn.keys()),但我得到了相同的输出:/
为什么订单会发生变化,我该如何解决?
【问题讨论】:
-
字典 在 Python 中没有顺序,恐怕你必须在创建列表或类似方法后对其进行排序......
标签: python arrays python-3.x dictionary collections