吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 695|回复: 0
收起左侧

[讨论] sorted()排序

[复制链接]
十好小学生 发表于 2021-8-4 17:36
问题描述:有一个整数列表,要求调整元素顺序,把所有奇数按大小顺序放到前面,偶数按大小顺序放到后面。

[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]
'''

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止回复与主题无关非技术内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-23 13:53

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表