Reputation: 171
I have a list in the format:
Apple, Orange[123 431]43351
Banana, Cherry[141 421]23423
Coconut, Mango[23 12312]232342
....
....
I want to sort the list according to the number after the bracket ']'. The output should be:
Banana, Cherry[141 421]23423
Apple, Orange[123 431]43351
Coconut, Mango[23 12312]232342
I am trying to sort the list by using this:
LIST.sort(key = lambda x: x.split()[1])
for item in LIST:
print(item)
I can find the last number by this: But I am not able to sort it
for item in LIST:
bracket_index = item.find("]")
end_of_line = item[bracket_index + 1:]
if bracket_index != -1:
print(end_of_line)
Upvotes: 0
Views: 54
Reputation: 27201
You can go with @Psidom's suggestion:
LIST.sort(key=lambda x: int(x.split(']')[1]))
Notice the use of int()
to ensure the sort is done numerically rather than by string comparisons (which are done lazily; i.e., '4321'
is considered "larger" than '20000000'
due to '4' > '2'
).
Full example:
LIST = [
'Apple, Orange[123 431]43351',
'Banana, Cherry[141 421]23423',
'Coconut, Mango[23 12312]232342'
]
LIST.sort(key=lambda x: int(x.split(']')[1]))
print(LIST)
A better method would be to parse your strings first. For example:
from collections import namedtuple
import re
FruitTuple = namedtuple('FruitTuple', ['fruit', 'color', 'num1', 'num2', 'num3'])
unparsed_list = [
'Apple, Orange[123 431]43351',
'Banana, Cherry[141 421]23423',
'Coconut, Mango[23 12312]232342'
]
split_list = [re.search('(\\w+), (\\w+)\\[(\\d+) (\\d+)\\](\\d+)', x).groups() for x in unparsed_list]
fruit_list = [FruitTuple(*x) for x in split_list]
fruit_list.sort(key=lambda x: int(x.num2))
print(fruit_list)
Produces:
[FruitTuple(fruit='Banana', color='Cherry', num1='141', num2='421', num3='23423'), FruitTuple(fruit='Apple', color='Orange', num1='123', num2='431', num3='43351'), FruitTuple(fruit='Coconut', color='Mango', num1='23', num2='12312', num3='232342')]
Upvotes: 0
Reputation: 36
What is the format of your list? Is it a list of tuples or a list of strings? This works:
a = ['Apple, Orange[123 431]43351',
'Banana, Cherry[141 421]23423',
'Coconut, Mango[23 12312]232342']
a.sort(key = lambda el: el.split(']')[1])
print(a)
Output:
['Coconut, Mango[23 12312]232342',
'Banana, Cherry[141 421]23423',
'Apple, Orange[123 431]43351']
If it is a list of pairs of strings instead, then you should use key = lambda el: el[1].split(']')[1]
like so:
a = [('Apple', 'Orange[123 431]43351'),
('Banana', 'Cherry[141 421]23423'),
('Coconut',' Mango[23 12312]232342')]
a.sort(key = lambda el: el[1].split(']')[1])
print(a)
Output:
[('Coconut', ' Mango[23 12312]232342'),
('Banana', 'Cherry[141 421]23423'),
('Apple', 'Orange[123 431]43351')]
Upvotes: 2