Skip to main content
 首页 » 编程设计

python之代码 : Code isn't working to sort through a list of 1 million integers, 打印前 10

2025年05月04日45lexus

这是作业,所以我必须尽可能少地使用 python 函数,但仍然允许计算机有效地处理 100 万个数字的列表。

#!/usr/bin/python3 
 
#Find the 10 largest integers 
#Don't store the whole list 
 
import sys 
import heapq 
 
def fOpen(fname): 
        try: 
                fd = open(fname,"r") 
        except: 
                print("Couldn't open file.") 
                sys.exit(0) 
        all = fd.read().splitlines() 
        fd.close() 
        return all 
 
words = fOpen(sys.argv[1]) 
 
numbs = map(int,words) 
print(heapq.nlargest(10,numbs)) 
 
li=[] 
count = 1 
 
 
 
#Make the list 
for x in words: 
        li.append(int(x)) 
        count += 1 
        if len(li) == 10: 
                break 
 
 
#Selection sort, largest-to-smallest 
for each in range(0,len(li)-1): 
        pos = each 
        for x in range(each+1,10): 
                if li[x] > li[pos]: 
                        pos = x 
                if pos != each: 
                        li[each],li[pos] = li[pos],li[each] 
 
for each in words: 
        print(li) 
        each = int(each) 
        if each > li[9]: 
                for x in range(0,9): 
                        pos = x 
                        if each > li[x]: 
                                li[x] = each 
                                for i in range(x+1,10): 
                                        li[pos],li[i] = li[i],li[pos] 
                                break 
 
 
#Selection sort, largest-to-smallest 
for each in range(0,len(li)-1): 
        pos = each 
        for x in range(each+1,10): 
                if li[x] > li[pos]: 
                        pos = x 
                if pos != each: 
                        li[each],li[pos] = li[pos],li[each] 
 
 
 
 
print(li) 

代码几乎按照我想要的方式工作。我试图从前 10 位数字创建一个列表。对它们进行排序,使其按降序排列。然后让 python 只检查列表,如果数字大于较小的数字(而不是读取列表 10(len(x))。

这是我应该得到的输出:

>>>[9932, 9885, 9779, 9689, 9682, 9600, 9590, 9449, 9366, 9081] 

这是我得到的输出:

>>>[9932, 9689, 9885, 9779, 9682, 9025, 9600, 8949, 8612, 8575] 

请您参考如下方法:

如果您只需要前 10 个数字,而不关心对整个列表进行排序。

如果 “必须尝试使用​​尽可能少的 python 函数” 意味着您(或您的教师)更愿意避免 heapq。

另一种方法是在只解析整个文件一次的同时跟踪前 10 个数字:

top = [] 
 
with open('numbers.txt') as f: 
 
    # the first ten numbers are going directly in 
    for line in f: 
        top.add(int(line.strip())) 
        if len(top) == 10: 
            break 
 
    for line in f: 
        num = int(line.strip()) 
        min_top = min(top) 
        if num > min_top:    # check if the new number is a top one 
            top.remove(min_top) 
            top.append(num) 
 
print(sorted(top)) 

更新:如果您真的不需要就地排序并且因为您只打算对 10 个数字进行排序,我会避免重新排序的痛苦。

我只是建立一个新列表,例如:

sorted_top = [] 
while top: 
    max_top = max(top) 
    sorted_top.append(max_top) 
    top.remove(max_top)