0

I have a list like this;

List = [('apple 5', 12), ('apple 3', 2), ('apple 6', 10),('apple 4', 15), ('apple 9', 11), ('apple 7', 14), ('apple 18', 10), ('apple 16', 10),('orange 5', 4), ('orange 4', 7)]

I know how to sort the list normally.

for i in sorted(List):
  print(i)

this gives;

('apple 16', 10)
('apple 18', 10)
('apple 3', 2)
('apple 4', 15)
('apple 5', 12)
('apple 6', 10)
('apple 7', 14)
('apple 9', 11)
('orange 4', 7)
('orange 5', 4)

But can I sort something like this?

('apple 3', 2)
('apple 4', 15)
('apple 5', 12)
('apple 6', 10)
('apple 7', 14)
('apple 9', 11)
('apple 16', 10)
('apple 18', 10)
('orange 4', 7)
('orange 5', 4)
0

2 Answers 2

3

You just need to assign your own key:

l1 = [('apple 5', 12), ('apple 3', 2), ('apple 6', 10),('apple 4', 15), ('apple 9', 11), ('apple 7', 14), ('apple 18', 10), ('apple 16', 10),('orange 5', 4), ('orange 4', 7)]

def sort_key(x):
    word, num = x[0].split()
    return word, int(num), x[1] # Sort by word, than the number as an integer, than the final number

l1.sort(key=sort_key)
print(*l1, sep='\n')

Output:

('apple 3', 2)
('apple 4', 15)
('apple 5', 12)
('apple 7', 14)
('apple 9', 11)
('apple 16', 10)
('apple 18', 10)
('orange 4', 7)
('orange 5', 4)
Sign up to request clarification or add additional context in comments.

Comments

2

You may use your own key to sort, and use multiples criterias, the syntax is sorted(values, key = lambda x: (criteria_1, criteria_2))

values = [('apple 5', 12), ('apple 3', 2), ('apple 6', 10), ('apple 4', 15),
          ('apple 9', 11), ('apple 7', 14), ('apple 18', 10), ('apple 16', 10),
          ('orange 5', 4), ('orange 4', 7)]

for i in sorted(values, key=lambda x: (x[0].split(" ")[0], int(x[0].split(" ")[1]))):
    print(i)

Or using a method to get a proper code

def splitter(v: str):
    s = v.split(" ")
    return s[0], int(s[1])

for i in sorted(values, key=lambda x: splitter(x[0])):
    print(i)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.