问题
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