Python以不正确的方式排序

时间:2016-03-07 18:28:44

标签: python list sorting

我的代码

class getCol:
    matrix = []
    def __init__(self, file, delim=" "):
        with open(file, 'rU') as f:
            getCol.matrix =  [filter(None, l.split(delim)) for l in f]

    def __getitem__ (self, key):
        column = []
        for row in getCol.matrix:
            try:
                column.append(row[key])
            except IndexError:
                # pass
                column.append("")
        return column

list1 = getCol('/home/milenko/EDIs/site1/newst2.txt')[0]
list2 = getCol('/home/milenko/EDIs/site2/newst2.txt')[0]
list3 = getCol('/home/milenko/EDIs/site3/newst2.txt')[0]
list4 = getCol('/home/milenko/EDIs/site4/newst2.txt')[0]
list5 = getCol('/home/milenko/EDIs/site5/newst2.txt')[0]
list6 = getCol('/home/milenko/EDIs/site6/newst2.txt')[0]
list7 = getCol('/home/milenko/EDIs/site7/newst2.txt')[0]
list8 = getCol('/home/milenko/EDIs/site8/newst2.txt')[0]
list9 = getCol('/home/milenko/EDIs/site9/newst2.txt')[0]
list10 = getCol('/home/milenko/EDIs/site10/newst2.txt')[0]
list11 = getCol('/home/milenko/EDIs/site11/newst2.txt')[0]
list12 = getCol('/home/milenko/EDIs/site12/newst2.txt')[0]
list13 = getCol('/home/milenko/EDIs/site13/newst2.txt')[0]
list14 = getCol('/home/milenko/EDIs/site14/newst2.txt')[0]
list15 = getCol('/home/milenko/EDIs/site15/newst2.txt')[0]

list_of_lists = []
list_of_lists.append(list1)
list_of_lists.append(list2)
list_of_lists.append(list3)
list_of_lists.append(list4)
list_of_lists.append(list5)
list_of_lists.append(list6)
list_of_lists.append(list7)
list_of_lists.append(list8)
list_of_lists.append(list9)
list_of_lists.append(list10)
list_of_lists.append(list11)
list_of_lists.append(list12)
list_of_lists.append(list13)
list_of_lists.append(list14)
list_of_lists.append(list15)

result = []

# Loop the inner lists from list_of_lists, this will be list1, list2, list3...
for inner_list in list_of_lists:
    # Loop each element of the inner lists
    for element in inner_list:
        # Make sure the element is not already in the result (this can also be done with sets)
        if element not in result:
            # Add the inner element to result
            result.append(element)

# Sort the result
result = sorted(result)
print("\n".join(map(str, result)))

但问题在这里

1.92413
10.15704
1026.00000
10260.00000
10672.43359
11.81549
1104.06055
114.21478
12.00000
12415.04102
1284.33289
13.74474
132.00000
132.86391
1376.00000
13760.00000
14442.18457
1494.04028
15.00000

我只想要从最小到最大的正常排序。我该如何解决这个问题?sort还有其他选择吗?

2 个答案:

答案 0 :(得分:3)

它按字符串排序。要按数字排序,请使用key参数:

result = sorted(result, key=float)

这会将每个字符串转换为浮点数以进行排序,但是会离开 数据原样。

由于您要将结果分配给相同的标识符,您还可以:

result.sort(key=float)

答案 1 :(得分:1)

您需要将列表中的值从字符串转换为数字类型,如浮点数。