python sort list using lambda function -
i have list 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 want sort based on 2 conditions:
sort no of "\" nowadays in string. by alphabets.my end result should 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 learning lambda function in python , wrote code:
print(sorted(mylist, key=lambda x:x.count("\\")))
but code sorts count of "\". not sort alphabets. result seeing key "'c:\users\ab.txt'" before key "'c:\users\aa.txt'".
i sort list 2 times, want in 1 line. should add together in lambda code ? since new whole "lambda" thing, cannot think of way this. replying!! :)
return sequence key function contains items want sort by.
key=lambda x: (x.count('\\'), x.split('\\'))
python-3.x
No comments:
Post a Comment