Python lambda return value put multiple conditions extended thinking (interview questions)

Interview questions, require lambda to achieve the following effect 
foo = [ -5, 8, 0, 4, 9, -4, -20, -2, 8, 2, -4]
Positive numbers from small to large , negative numbers from large To the small

answer:
res=sorted(foo,key=lambda x:(x<0 ,abs(x)))
print(res)

Starting to think about lambda from this,
lambda x: x is
equivalent to
def func (x):
  return x

when sorted (foo, key = lambda x: (x < 0, abs (x)))
will follow x <0, sorted in the order of abs (x)

res=sorted(foo,key=lambda x:(x>0 ,x%2,abs(x)))
print(res)
You can even add a layer of conditions

Guess you like

Origin www.cnblogs.com/zhaolei1986/p/12711978.html