Python heapq 提供意外的输出
我有一个简单的 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
堆中每个元组的第一个元素是字符串,而不是整数。因此,使用字典顺序比较,而不是基础值的比较。
如果要根据字符串代表的数值进行比较,请更改
为
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
to