简体   繁体   English

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

[英]how do I sort a list using itemgetter

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)

I am trying to sort the list by getting the first item in each small list. 我正在尝试通过获取每个小列表中的第一项来对列表进行排序。 But instead of getting the right answer, here is what I got: 但是,没有得到正确的答案,这就是我得到的:

[['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']]

The problem is the list is sorted by the first character of item 1 in each small list. 问题是列表按每个小列表中项目1的第一个字符排序。 For example, 89779405 is less than 873955477. 例如,89779405小于873955477。

How can I solve this problem? 我怎么解决这个问题?

You either need to convert the sublists to lists of integers, like this: 您要么需要将子列表转换为整数列表,如下所示:

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

Or use a key function that converts the element to an integer: 或使用将元素转换为整数的键函数:

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

I don't think it makes sense to use itemgetter in the second case because the is no built-in function composition operator, so you can write int o itemgetter(0) . 我不认为在第二种情况下使用itemgetter是没有意义的,因为没有内置函数组合运算符,因此您可以将int o itemgetter(0)编写为int o itemgetter(0)

You can pass a lambda (unnamed function) that converts the first element of the list into int into key . 您可以传递一个lambda (未命名函数),该函数将列表的第一个元素转换为intkey

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)

I think, this is you needed, 我认为,这是您需要的,

from operator import itemgetter


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM