Rash
Rash

Reputation: 8197

python sort list using lambda function

I have a list like this:

[
    'C:\\Users\\Rash\\Downloads\\Programs\\a.txt',
    'C:\\Users\\Rash\\Downloads\\a.txt',
    'C:\\Users\\Rash\\a.txt',
    'C:\\Users\\ab.txt',
    'C:\\Users\\aa.txt'
]

and I want to sort it based on two conditions:

  1. Sort by no of "\" present in the string.
  2. By Alphabets.

My end result should be this:

[
    'C:\\Users\\aa.txt',
    'C:\\Users\\ab.txt',
    'C:\\Users\\Rash\\a.txt',
    'C:\\Users\\Rash\\Downloads\\a.txt',
    'C:\\Users\\Rash\\Downloads\\Programs\\a.txt'
]

I am just learning lambda function in python and wrote this code:

print(sorted(mylist, key=lambda x:x.count("\\")))

but this code only sorts by count of "\". It does not sort it by alphabets. The result is that I am seeing the key "'C:\Users\ab.txt'" before the key "'C:\Users\aa.txt'".

I could sort the list two times, but I want to do it in one line. What should I add in the lambda code ? Since I am new to this whole "lambda" thing, I cannot think of a way to do this. Thanks for replying!! :)

Upvotes: 0

Views: 4359

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798566

Return a sequence from the key function that contains the items you want to sort by.

key=lambda x: (x.count('\\'), x.split('\\'))

Upvotes: 3

Related Questions