字符分类排序需求的Python实现代码能否进一步精简缩短?
你的实现逻辑是完全正确的,核心思路就是先分类再排序拼接,代码可以做以下简化:
优化点说明
- 无需将输入字符串转为列表后按索引遍历,直接迭代字符串本身即可拿到每一个字符
- 无需单独声明4个空列表存储分类结果,可直接用生成器表达式筛选对应类别字符后传入
sorted()处理 - 省略不必要的中间变量赋值,直接在拼接阶段完成筛选、排序、转字符串的操作
简化后代码
raw = input().strip() result = ''.join(sorted(c for c in raw if c.islower())) + \ ''.join(sorted(c for c in raw if c.isupper())) + \ ''.join(sorted(c for c in raw if c.isdigit() and int(c) % 2)) + \ ''.join(sorted(c for c in raw if c.isdigit() and not int(c) % 2)) print(result)
如果追求极端的简洁性,也可以借助排序key的自定义规则实现一行写完(可读性略低,按需选择):
print(''.join(sorted(input().strip(), key=lambda c: (0 if c.islower() else 1 if c.isupper() else 2 if c.isdigit() and int(c)%2 else 3, c))))
内容的提问来源于stack exchange,提问作者Jeet B. Lahiri
相关产品推荐
相关产品推荐

