在给定数字文件中查找次数最多、查找最大数

基于给定代码生成数字文件number.txt 读出numbres.txt中所有的数据,(1)查找出出现次数最多的50个数,并将这些数写入文件top50.txt;(2)查找出最大的50个数,并将这些书写入max50.txt。

使用random模块生成1000个1到100的整数,用来模拟从numbers.txt中读入数据

from random import randint
numbers = [randint(1,100) for _ in range(1000)]

from collections import Counter
res = sorted(Counter(numbers).items(), key=lambda x:x[1], reverse=True)
top50 = [i[0] for i in res[:50]]
max50 = sorted(numbers, reverse=True)[:50]

代码如下,如有帮助,请点击一下采纳谢谢


with open("c:/aaa/number.txt","r",encoding="utf-8") as file:
    nums = file.readlines()
    nums = [int(num) for num in nums]

dict_temp = {}
for num in nums:
    if num in dict_temp.keys():
        dict_temp[num] += 1
    else:
        dict_temp[num] = 0
with open("c:/aaa/top50.txt","w",encoding="utf-8") as file:
    a = sorted(dict_temp.items(), key=lambda x: x[1], reverse=True)[:50]
    for temp in a:
        file.write(str(temp[0]) + '\n')

nums = list(set(nums))
nums = sorted(nums, reverse=True)
with open("c:/aaa/max50.txt","w",encoding="utf-8") as file:
    for num in nums[:50]:
        file.write(str(num)+ '\n')

同学,老师的作业 你提交了吗,我还是运行不出来。