6

我在 python 中有一个字符串列表,如下所示:

  • 姓名 号码 号码 4 位数字

如何按最后一个数字对其进行排序?

4

3 回答 3

20

像那样:

sorted(your_list, lambda x: int(x.split()[-1]))
于 2013-04-22T15:29:14.780 回答
18
my_list = ['abc 12 34 3333',
           'def 21 43 2222',
           'fgh 21 43 1111']

my_list.sort(key=lambda x:int(x.split()[-1]))

my_list就是现在:['fgh 21 43 1111', 'def 21 43 2222', 'abc 12 34 3333']

于 2013-04-22T15:28:58.687 回答
0
def sort_csv(lines=[], delim=',', position=1):
    '''
    Returns a sorted list based on "column" from csv-type data.
    '''
    return sorted(lines, key=lambda x: x.split(delim)[int(position) - 1])


test_data = [
        'part1/foo/part1/partX',
        'part3/bar/part5/partX',
        'part4/fuz/partA/partX',
        'part2/buz/part3/partX',
        ]
# Sort by third element
pprint(sort_csv(test_data, '/', 3))
#['part1/foo/part1/partX',
# 'part2/buz/part3/partX',
# 'part3/bar/part5/partX',
# 'part4/fuz/partA/partX']

test_data = [
        'abc 12 34 3333',
        'bar 53 29 AAAA',
        'def 21 43 2222',
        'foo 53 29 5555',
        'fgh 21 43 1111',
]
# Sort by last element
pprint(sort_csv(test_data, ' ', 0))
#['fgh 21 43 1111',
# 'def 21 43 2222',
# 'abc 12 34 3333',
# 'foo 53 29 5555',
# 'bar 53 29 AAAA']
于 2018-10-21T18:57:01.610 回答