[英]Python Insertion sort algorithm doesn't arrange floating point numbers in file properly
My algorithm places some numbers in my file incorrectly, for example: 10015.0 before 1006.8765我的算法在我的文件中错误地放置了一些数字,例如:1006.8765 之前的 10015.0
#My insertion sort algorithm
def insertion_sort(float_list):
for i in range(1, len(float_list)):
key = float_list[i]
j = i-1
while j >= 0 and key < float_list[j]:
float_list[j+1] = float_list[j]
j -= 1
float_list[j+1] = key
return float_list
#Turning strings in file into floats
with open("floats.txt", "r") as f:
lst = f.read().splitlines()
[float (i) for i in lst]
print(lst)
insertion_sort(lst)
print(lst)
#writing into new file
with open("sorted_floats.txt", "w") as sorted_floats:
sorted_floats.write(str(lst))
This line doesn't do anything: [float (i) for i in lst]
此行不执行任何操作:
[float (i) for i in lst]
Because you aren't converting your inputs from strings to floats, your code is sorting the lines of the file alphabetically rather than numerically.因为您没有将输入从字符串转换为浮点数,所以您的代码按字母顺序而不是数字顺序对文件的行进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.