0
lst = ["g1 act car", "a8 act zoo", "a2 act car"]

I want to sort a list such that:

  1. Ignoring 1st token of each string, strings are ordered lexicographically
  2. If there's a tie, order as per the 1st token

Above list after sorting should be as follows:

lst = ["a2 act car", "g1 act car", "a8 act zoo"]

I want to write the sorting code in a single line. I can write the code for the 1st condition as follows:

lst = sorted(lst, key = lambda x : x.split()[1])

How can I combine the second condition as well in this lambda expression?

3 Answers 3

2

Try using:

lst = sorted(lst, key = lambda x : (x.split(None, 1)[1], x.split()[0]))

And now:

print(lst)

Is:

['a2 act car', 'g1 act car', 'a8 act zoo']
Sign up to request clarification or add additional context in comments.

Comments

1

I would do it following way:

lst = ["g1 act car","a8 act zoo","a2 act car"]
lst = sorted(lst, key=lambda x:x.split(None,1)[::-1])
print(lst)

Output:

['a2 act car', 'g1 act car', 'a8 act zoo']

Explanation: x.split(None,1) cut at first space (or other seperator), so I get list with 1st token and rest, then I reverse them, so [rest, 1st token] are used as key, therefore it sorts by rest and then 1st token in case same rest appear more than once.

Comments

0

Try using:

lst = sorted(lst, key = lambda x : [x.split()[1:], x.split()[0]])

And now:

lst

The result as follow:

['a2 act car', 'g1 act car', 'a8 act zoo']

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.