[英]Sorting numbers correctly with a mixed list without sort()
在我的练习中,我做了一个排序算法。 我有一个文本文件并将其放入列表中。
text = file.read().split()
像这样。 所以意味着我的列表包含字符串形式的数字和字母。
def insertion_sort(self, arr):
for i in range(1, len(arr)):
val = arr[i] #value
pos = i #position
while pos > 0 and val < arr[pos-1] :
arr[pos] = arr[pos-1] #Move elements ahead
pos -= 1
arr[pos] = val #sort the value to the correct position
当然,该算法现在对数字进行了错误的排序。 正确排序的最佳解决方案是什么?
编辑:我的字符串例如:[“1”,“e”,“2”,“d”,“10”] - 我得到的 Output:1,10,2,d,e - 我想要的 Output:1 ,2,10,d,e
只需对代码进行最少的更改,您就可以从列表中提取“数字”并使用完全相同的算法。 例如:
def insertion_sort(arr):
arr_num = []
arr_str = []
# if the value is a number, then add it to arr_num, else to arr_str
for val in arr:
try:
arr_num.append(float(val))
except:
arr_str.append(val)
#your algorithm applied to arr_num
for i in range(1, len(arr_num)):
val = arr_num[i] #value
pos = i #position
while pos > 0 and val < arr_num[pos-1] :
arr_num[pos] = arr_num[pos-1] #Move elements ahead
pos -= 1
arr_num[pos] = val #sort the value to the correct position
#To convert back to string if needed
for i,val in enumerate(arr_num):
arr_num[i] = str(val)
#To concatenate list of numbers and string if needed
arr = arr_num+arr_str
return arr
我得到:
a = ["7", "c", "b", "10", "a"]
insertion_sort(a)
Out[57]: ['7.0', '10.0', 'c', 'b', 'a']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.