Sorting strings by a substring in Python [duplicate]

孤街浪徒 提交于 2020-11-27 01:57:16

问题


I have a list of strings in python that looks like this:

  • Name number number 4-digit number

How can I sort it by the last number?


回答1:


Like that:

sorted(your_list, lambda x: int(x.split()[-1]))



回答2:


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 is now: ['fgh 21 43 1111', 'def 21 43 2222', 'abc 12 34 3333']




回答3:


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


来源:https://stackoverflow.com/questions/16150868/sorting-strings-by-a-substring-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!