Does lambda not change value when using key=
in sort()
function?
nas = [1,2,3,4,5]
nas.sort(key=lambda a: a + 1)
print(nas)
nas
still has same value why didn't get 1 added using lambda?
As the name might suggest, sort
only... sorts
. It won't change any of the elements from the lambda you provide it. That lambda is only used to define how elements of your list should be sorted.
So for example, when trying to compare 3
and 4
, your lambda instructs it to compare 3
as if it were 4
, and 4
as if it were 5
. Of course, this would have the same impact of just comparing the integers directly:
nas = [1,2,3,4,5]
nas.sort(key=lambda a: a + 1) # Or just `nas.sort()`
print(nas)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.