簡體   English   中英

使用沒有 sort() 的混合列表正確排序數字

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM