冒泡排序未产生所需的输出
Bubble sort not producing desired output
import csv
names = []
scores = []
length = 0
with open('table.csv') as csvfile:
read = csv.reader(csvfile, delimiter = ',')
for row in read:
name = row[0]
score = row[1]
length = length + 1
names.append(name)
scores.append(score)
print(names)
print(scores) #printing unsorted list
#using bubble sort
done = 0
while done != 1:
done = 1
for i in range(length - 1):
if scores[i] > scores[i +1]:
scores[i],scores[i+1] = scores[i + 1], scores[i]
names[i],names[i+1] = names[i + 1], names[i]
done = 0
print("")
print(names)
print(scores)
Click here to access image that shows the output of the code
此代码旨在打印出我正在开发的游戏的最高分 table。
我知道使用冒泡排序效率很低,但我只是暂时尝试一下。
所以基本上代码的问题在于它对它们进行排序,但如果数字大于 100,000,它似乎会跳过最后一个零并将其排序,就好像它是 10000
我在想循环次数可能有问题,或者超过 100000 次通常会被写成 100,000 次弄乱 csv 文件,但老实说我不知道。
问题是在读取 csv 文件时,您得到的是字符串。然后,冒泡排序正在进行字典排序,而不是您正在寻找的数字排序。
要修复它,请将分数转换为 int
(假设分数是整数),如下所示
score = int(row[1])
然后它应该可以正常工作了。
在 if
语句中,您比较的是 strings
,而不是 int
。尝试替换
if scores[i] > scores[i +1]:
和
if int(scores[i]) > int(scores[i +1]):
数字被存储为字符串,这导致您的排序将所有 1 视为第一个而不是它们的整数值
我认为这是因为它们是按字符串值而不是数字(例如整数)处理的。因此比较是在第一个字符上进行的,在 100,000 的情况下是“1”。例如,按照这个逻辑,55,000 大于 100,000,因为 5 大于 1。
希望这对您有所帮助,让我知道进展如何!
import csv
names = []
scores = []
length = 0
with open('table.csv') as csvfile:
read = csv.reader(csvfile, delimiter = ',')
for row in read:
name = row[0]
score = row[1]
length = length + 1
names.append(name)
scores.append(score)
print(names)
print(scores) #printing unsorted list
#using bubble sort
done = 0
while done != 1:
done = 1
for i in range(length - 1):
if scores[i] > scores[i +1]:
scores[i],scores[i+1] = scores[i + 1], scores[i]
names[i],names[i+1] = names[i + 1], names[i]
done = 0
print("")
print(names)
print(scores)
Click here to access image that shows the output of the code
此代码旨在打印出我正在开发的游戏的最高分 table。 我知道使用冒泡排序效率很低,但我只是暂时尝试一下。 所以基本上代码的问题在于它对它们进行排序,但如果数字大于 100,000,它似乎会跳过最后一个零并将其排序,就好像它是 10000 我在想循环次数可能有问题,或者超过 100000 次通常会被写成 100,000 次弄乱 csv 文件,但老实说我不知道。
问题是在读取 csv 文件时,您得到的是字符串。然后,冒泡排序正在进行字典排序,而不是您正在寻找的数字排序。
要修复它,请将分数转换为 int
(假设分数是整数),如下所示
score = int(row[1])
然后它应该可以正常工作了。
在 if
语句中,您比较的是 strings
,而不是 int
。尝试替换
if scores[i] > scores[i +1]:
和
if int(scores[i]) > int(scores[i +1]):
数字被存储为字符串,这导致您的排序将所有 1 视为第一个而不是它们的整数值
我认为这是因为它们是按字符串值而不是数字(例如整数)处理的。因此比较是在第一个字符上进行的,在 100,000 的情况下是“1”。例如,按照这个逻辑,55,000 大于 100,000,因为 5 大于 1。
希望这对您有所帮助,让我知道进展如何!