如何使用itemgetter对列表进行排序

时间:2018-07-25 05:54:53

标签: python python-3.x

from operator import itemgetter

c = [['29325493', '491963279'], ['665431604', '107866412'],
    ['572747824', '834468627'], ['623075369', '146360674'],
    ['958964458', '525879903'], ['977175138', '523647968'],
    ['689471337', '580279579'], ['664237570', '288339955'],
    ['328743490', '207620319'], ['315386742', '528392695'],
    ['95567418', '163424206'], ['873955477', '450413794'],
    ['7616943', '842564675'], ['575682685', '33126205'],
    ['89779405', '844288987']]

c.sort(key=itemgetter(0),reverse=True)
print(c)

我正在尝试通过获取每个小列表中的第一项来对列表进行排序。但是,没有得到正确的答案,这就是我得到的:

[['977175138', '523647968'],['958964458', '525879903'],
['95567418', '163424206'], ['89779405', '844288987'],
['873955477', '450413794'], ['7616943', '842564675'],
['689471337', '580279579'], ['665431604', '107866412'],
['664237570', '288339955'], ['623075369', '146360674'],
['575682685', '33126205'], ['572747824', '834468627'],
['328743490', '207620319'], ['315386742', '528392695'],
['29325493', '491963279']]

问题是列表按每个小列表中项目1的第一个字符排序。例如,89779405小于873955477。

如何解决此问题?

3 个答案:

答案 0 :(得分:2)

您需要将子列表转换为整数列表,如下所示:

c = [[int(elem) for elem in l] for l in c]
c.sort(key=itemgetter(0),reverse=True)

或使用将元素转换为整数的键函数:

c.sort(key=lambda l:int(l[0]),reverse=True)

在第二种情况下,我认为使用itemgetter没有意义,因为该函数不是内置函数组合运算符,因此您可以编写int o itemgetter(0)

答案 1 :(得分:0)

您可以传递lambda(未命名函数),该函数将列表的第一个元素转换为int并转换为key

c = [['29325493', '491963279'], ['665431604', '107866412'],
    ['572747824', '834468627'], ['623075369', '146360674'],
    ['958964458', '525879903'], ['977175138', '523647968'],
    ['689471337', '580279579'], ['664237570', '288339955'],
    ['328743490', '207620319'], ['315386742', '528392695'],
    ['95567418', '163424206'], ['873955477', '450413794'],
    ['7616943', '842564675'], ['575682685', '33126205'],
    ['89779405', '844288987']]
c.sort(key=lambda x: int(x[0]), reverse=True)
print(c)

答案 2 :(得分:0)

我认为,这是您需要的

from operator import itemgetter


sorted(c, key=itemgetter(0,0))