Python按字母顺序对字符串排序,小写优先 [英] Python sort strings alphabetically, lowercase first

查看:782
本文介绍了Python按字母顺序对字符串排序,小写优先的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用python按字母顺序对给定的字符串数组进行排序,但小写单词应首先出现.

I want to sort a given array of strings alphabetically using python, but lowercase words should appear first.

一个例子:

#!/usr/local/bin/python2.7
arr=['A','e','a','D','f','B']
arr.sort()
for s in arr: print s

输入:

A
e
a
D
f
B

输出(当前):

A
B
D
a
e
f

输出(应该是):

a
e
f
A
B
D

推荐答案

使用自定义键方法检查项目是否不是.lower(),然后比较项目本身.对于'A''D''B' not x.islower()将返回True,对于其他False,则返回False,因为True > False小写字母的项目将首先出现:

Use a custom key method which checks whether the item is not .lower() and then compares the items itself. For 'A', 'D' and 'B' not x.islower() will return True and for other it is False, as True > False smaller case items will come first:

>>> arr = ['A','e','a','D','f','B']
>>> arr.sort(key=lambda x:(not x.islower(), x))
>>> arr
['a', 'e', 'f', 'A', 'B', 'D']

这篇关于Python按字母顺序对字符串排序,小写优先的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆