好友
阅读权限10
听众
最后登录1970-1-1
|
问题描述:有一个整数列表,要求调整元素顺序,把所有奇数按大小顺序放到前面,偶数按大小顺序放到后面。
[Python] 纯文本查看 复制代码 from random import randint
x = [randint(1,100) for i in range(20)]
print(x)
y=sorted(x, key=lambda item:-(item%2*100)+item)
print(y)
'''
[43, 81, 15, 26, 76, 21, 21, 9, 56, 38, 90, 71, 18, 38, 19, 64, 60, 51, 90, 36]
[9, 15, 19, 21, 21, 43, 51, 71, 81, 18, 26, 36, 38, 38, 56, 60, 64, 76, 90, 90]
[Finished in 102ms]
'''
也可以
[Python] 纯文本查看 复制代码 from random import randint
x = [randint(1,100) for i in range(20)]
print(x)
#y=sorted(x, key=lambda item:-(item%2*100)+item)
y=sorted(x, key=lambda item:(item%2==0,item))
print(y)
'''
[40, 77, 7, 66, 40, 65, 46, 24, 31, 81, 80, 69, 77, 26, 39, 28, 6, 33, 39, 90]
[7, 31, 33, 39, 39, 65, 69, 77, 77, 81, 6, 24, 26, 28, 40, 40, 46, 66, 80, 90]
[Finished in 103ms]
''' |
|