Reputation: 8197
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:
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
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