对字符串列表进行排序,忽略大小写 [英] Sort list of strings ignoring upper/lower case

查看:174
本文介绍了对字符串列表进行排序,忽略大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,其中包含代表动物名称的字符串.我需要对列表进行排序.如果使用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.

这篇关于对字符串列表进行排序,忽略大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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