问题描述
我有一个列表,其中包含代表动物名称的字符串.我需要对列表进行排序.如果使用sorted(list)
,它将首先使用大写字符串然后使用小写形式提供列表输出.
I have a list which contains strings representing animal names. I need to sort the list. If I use sorted(list)
, it will give the list output with uppercase strings first and then lowercase.
但是我需要下面的输出.
But I need the below output.
输入:
var = ['ant','bat','cat','Bat','Lion','Goat','Cat','Ant']
输出:
['ant', 'Ant', 'bat', 'Bat', 'cat', 'Cat', 'Goat', 'Lion']
推荐答案
sort()
方法和sorted()
函数采用关键参数:
The sort()
method and the sorted()
function take a key argument:
var.sort(key=lambda v: v.upper())
为每个值调用key
中命名的函数,并在排序时使用返回值,而不会影响实际值:
The function named in key
is called for each value and the return value is used when sorting, without affecting the actual values:
>>> var=['ant','bat','cat','Bat','Lion','Goat','Cat','Ant']
>>> sorted(var, key=lambda v: v.upper())
['ant', 'Ant', 'bat', 'Bat', 'cat', 'Cat', 'Goat', 'Lion']
要在ant
之前对Ant
进行排序,您必须在键中包含更多信息,以便以给定的顺序对相等的值进行排序:
To sort Ant
before ant
, you'd have to include a little more info in the key, so that otherwise equal values are sorted in a given order:
>>> sorted(var, key=lambda v: (v.upper(), v[0].islower()))
['Ant', 'ant', 'Bat', 'bat', 'Cat', 'cat', 'Goat', 'Lion']
更复杂的密钥为Ant
生成('ANT', False)
,为ant
生成('ANT', True)
; True
排在False
之后,因此大写单词排在它们的小写字母之前.
The more complex key generates ('ANT', False)
for Ant
, and ('ANT', True)
for ant
; True
is sorted after False
and so uppercased words are sorted before their lowercase equivalent.
有关更多信息,请参见 Python排序方法.
See the Python sorting HOWTO for more information.
这篇关于对字符串列表进行排序,忽略大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!