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:
- Sort by no of "\" present in the string.
- 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!! :)
lambda <args>: <expr>is nearly the same asdef (<args>): return <expr>. The two differences are 1) the expression can be use in other statements and 2) the resulting function object gets the generic name '<lambda>' and does not get bound to a namespace name.