Python heapq 提供意外的输出

发布于 2025-01-14 14:48:53 字数 949 浏览 4 评论 0原文

我有一个简单的 python 脚本,旨在读取 csv 文件中的所有行并根据每行的第二个元素执行堆排序。 这是我读取文件的函数:

def read Processes():
    file = open('Project1/Processes/sample.csv', 'r')
    reader = csv.reader(file, delimiter=',')
    processes = []
    for row in reader:
    heapq.heappush(processes,(row[1],row))
return processes

以下是我打印数据的方式:

processess = readProcesses()
while processess:
    print(heapq.heappop(processess))

数据的初始输出是:

('10016', ['90', '10016', '8070'])
('10136', ['0', '10136', '11315'])
('10461', ['83', '10461', '79576'])
('10969', ['206', '10969', '52071'])
('2997', ['58', '2997', '12935'])
('3666', ['108', '3666', '98952'])
('3946', ['109', '3946', '22268'])
('4083', ['236', '4083', '81516'])
('4233', ['182', '4233', '28817'])
('4395', ['64', '4395', '94292'])
('4420', ['51', '4420', '52133'])

本质上,所有超过 10,000 的值都出现在堆的顶部。其余值按适当的顺序排列。我尝试在添加所有进程后调用 heapify 但没有效果。

I have a simple python script that aims to read all rows in a csv file and perform a heap sort based on the second element of each row.
Here is my function to read the file:

def read Processes():
    file = open('Project1/Processes/sample.csv', 'r')
    reader = csv.reader(file, delimiter=',')
    processes = []
    for row in reader:
    heapq.heappush(processes,(row[1],row))
return processes

And here is how I am printing the data:

processess = readProcesses()
while processess:
    print(heapq.heappop(processess))

The initial output for the data is:

('10016', ['90', '10016', '8070'])
('10136', ['0', '10136', '11315'])
('10461', ['83', '10461', '79576'])
('10969', ['206', '10969', '52071'])
('2997', ['58', '2997', '12935'])
('3666', ['108', '3666', '98952'])
('3946', ['109', '3946', '22268'])
('4083', ['236', '4083', '81516'])
('4233', ['182', '4233', '28817'])
('4395', ['64', '4395', '94292'])
('4420', ['51', '4420', '52133'])

Essentially, all values over 10,000 appear at the top of the heap. The rest of the values are in the appropriate order. I've tried calling heapify after adding all of the processes but it has no effect.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏了南城 2025-01-21 14:48:53

堆中每个元组的第一个元素是字符串,而不是整数。因此,使用字典顺序比较,而不是基础值的比较。

如果要根据字符串代表的数值进行比较,请更改

heapq.heappush(processes,(row[1],row))

heapq.heappush(processes,(int(row[1]),row))

The first element of each tuple in your heap is a string, not an integer. Thus, lexicographical comparison is used, rather than a comparison of the underlying values.

If you want to compare based on the numerical values that the strings represent, change

heapq.heappush(processes,(row[1],row))

to

heapq.heappush(processes,(int(row[1]),row))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文