不区分大小写的列表排序,而不小写结果? [英] case-insensitive list sorting, without lowercasing the result?

查看:30
本文介绍了不区分大小写的列表排序,而不小写结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的字符串列表:

['Aden', 'abel']

我想对项目进行排序,不区分大小写.所以我想得到:

['abel', 'Aden']

但我用 sorted()list.sort() 得到相反的结果,因为大写出现在小写之前.

我怎样才能忽略这个案例?我见过涉及小写所有列表项的解决方案,但我不想更改列表项的大小写.

解决方案

在 Python 3.3+ 中有 str.casefold 专为无壳匹配设计的方法:

sorted_list = sorted(unsorted_list, key=str.casefold)

在 Python 2 中使用 lower():

sorted_list = sorted(unsorted_list, key=lambda s: s.lower())

它适用于普通和 unicode 字符串,因为它们都有一个 lower 方法.

在 Python 2 中,它适用于普通字符串和 unicode 字符串的混合,因为这两种类型的值可以相互比较.然而,Python 3 不是这样工作的:你不能比较字节字符串和 unicode 字符串,所以在 Python 3 中你应该做明智的事情,只对一种类型的字符串列表进行排序.

<预><代码>>>>lst = ['亚丁', u'abe1']>>>排序(lst)['亚丁',你'abe1']>>>排序(lst,key = lambda s:s.lower())[u'abe1', '亚丁']

I have a list of strings like this:

['Aden', 'abel']

I want to sort the items, case-insensitive. So I want to get:

['abel', 'Aden']

But I get the opposite with sorted() or list.sort(), because uppercase appears before lowercase.

How can I ignore the case? I've seen solutions which involves lowercasing all list items, but I don't want to change the case of the list items.

解决方案

In Python 3.3+ there is the str.casefold method that's specifically designed for caseless matching:

sorted_list = sorted(unsorted_list, key=str.casefold)

In Python 2 use lower():

sorted_list = sorted(unsorted_list, key=lambda s: s.lower())

It works for both normal and unicode strings, since they both have a lower method.

In Python 2 it works for a mix of normal and unicode strings, since values of the two types can be compared with each other. Python 3 doesn't work like that, though: you can't compare a byte string and a unicode string, so in Python 3 you should do the sane thing and only sort lists of one type of string.

>>> lst = ['Aden', u'abe1']
>>> sorted(lst)
['Aden', u'abe1']
>>> sorted(lst, key=lambda s: s.lower())
[u'abe1', 'Aden']

这篇关于不区分大小写的列表排序,而不小写结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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