I'm having trouble understanding sorting by key using lambda function.
l = ['mix', 'xyz', 'apple', 'xanadu', 'aardvark']
print('Unsorted:%s' % l)
lSorted = sorted(l)
print('Sorted:%s' % lSorted)
lFinalSort = sorted(lSorted, key=lambda a : 'x' != a[0])
print('Final Sort:%s' % lFinalSort)
lFinalSort = sorted(lSorted,
Is the list we're sorting. key=
is the special 'contingency' we're sorting by. lambda a :
is a temporary function with a
being an arbitrary argument. 'x' != a[0]
This is the part that doesn't make sense on how it prioritizes sorting by 'x'
first. If 'x'
does not equal the first letter in the item we're sorting, sort by it?
In that case, why doesn't:
lFinalSort = sorted(lSorted, key=lambda a : 'd' in a)
sort by all words that contain 'd'
first?
And why does:
lFinalSort = sorted(lSorted, key=lambda a : 'd' in a[0])
bring 'aardvark'
to the front but leaves 'xanadu'
second to last?
source https://stackoverflow.com/questions/71563015/why-does-this-lambda-function-work-for-sorting-by-x-but-not-d
Comments
Post a Comment