【问题标题】:Sorting in python is not working [duplicate]在python中排序不起作用[重复]
【发布时间】:2017-01-30 12:38:37
【问题描述】:

这是我的完整代码示例:

import csv
import operator

f=open('C://Users//ganesha//Desktop//b//sampleDataCsv.csv',"r")
readerObject1 = csv.reader(f,delimiter = ",")    
inputList = list(readerObject1)    
print("Input",inputList)

sortedList = sorted(inputList,key=operator.itemgetter(0),reverse=True)

print("Output",sortedList)

f1=open('C://Users//ganesha//Desktop//b//sampleDataCsv4.csv',"w+") 
writerObject=csv.writer(f1,delimiter=",",lineterminator='\n')

writerObject.writerows(sortedList)

我的输入如下所示:

[['20'], ['12'], ['13'], ['11'], ['14'], ['15'], ['19'], ['1'], ['2'], ['4'], ['9'], ['0'], ['8'], ['7'], ['5'], ['6'], ['3'], ['16'], ['17'], ['10']]

我的输出是这样的:

[['9'], ['8'], ['7'], ['6'], ['5'], ['4'], ['3'], ['20'], ['2'], ['19'], ['17'], ['16'], ['15'], ['14'], ['13'], ['12'], ['11'], ['10'], ['1'], ['0']]

【问题讨论】:

    标签: python python-3.x sorting


    【解决方案1】:

    嗯,那是因为您正在对代表数字的strs 进行排序。创建一个小的 lambda 获取项目并将其强制转换为 int 以获得基于 int 值的排序:

    k = lambda x: int(x[0])    
    sortedList = sorted(inputList,key=k,reverse=True)
    

    现在sortedList 根据int 值排序:

    [['20'], ['19'], ['17'], ['16'], ['15'], ['14'], ['13'], ['12'],
     ['11'], ['10'], ['9'], ['8'], ['7'], ['6'], ['5'], ['4'], ['3'],
     ['2'], ['1'], ['0']]
    

    如果您不介意一些卷积,请将 lambda 直接放在对 sorted 的调用中:

    sortedList = sorted(inputList, key=lambda x: int(x[0]), reverse=True)
    

    【讨论】:

    • 在函数调用中使用 lambda 函数,如果它只使用一次。
    猜你喜欢
    • 2016-12-12
    • 2021-09-04
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多