简体   繁体   English

将str.lower用作list.sort的键有什么作用?

[英]What does passing str.lower as the key to list.sort do?

def Sorting(lst):
    lst.sort(key=str.lower)
    lst.sort(key=len)
    return lst

lst = ["Ronit", "Dan", "Yael"]
print Sorting(lst)

This code sorts the list alphabetically then by length. 此代码按字母顺序然后按长度对列表进行排序。 I was wondering why is it "lower"? 我想知道为什么它会“降低”? is it not going to work with upper case letters? 大写字母不起作用吗? what is it for? 这是为了什么

It performs case insensitive sorting . 它执行不区分大小写的排序

Let's modify your example a bit, to include another entry "dan": 让我们稍微修改一下示例,以包含另一个条目“ dan”:

lst = ['Ronit', 'Dan', 'dan']

Naturally, you'd expect "Dan" and "dan" to occur together. 自然,您希望“丹”和“丹”一起出现。 But they don't, because of the properties of string ordering. 但是,由于字符串排序的属性,它们不是。 Instead, a plain list.sort call will give you: 相反,普通的list.sort调用将为您提供:

lst.sort()
print(lst)
['Dan', 'Ronit', 'dan']

On the other hand, specifying str.lower gives you this: 另一方面,指定str.lower给您以下内容:

lst.sort(key=str.lower)
print(lst)
['Dan', 'dan', 'Ronit']

Here, the original list elements are sorted with respect to their lowercased equivalents. 在此,原始列表元素是根据其小写字母等效项进行排序的。

The second list.sort call with len should now be self-explanatory, assuming you understand what key does (yes, sort by length). 现在,假设您了解key作用(是,按长度排序),第二个带有len list.sort调用现在应该是不言自明的。


To understand why the first is needed before the second, consider another contrived example: 要了解为什么在第二个之前需要第一个,请考虑另一个人为的示例:

lst = ['Ronit', 'Dan', 'ram', 'dan']

First, consider just key=len : 首先,只考虑key=len

lst.sort(key=len)
print(lst)
['Dan', 'ram', 'dan', 'Ronit']

That "ram" looks out of place here. 那个“公羊”在这里看起来不合适。 THIS IS PRECISELY WHY WE HAVE THE FIRST STEP. 这正是我们为什么要迈出第一步的原因。 Now, adding in that step makes our output a lot more sensible. 现在,增加这一步使我们的输出更加明智。

lst.sort(key=str.lower)
lst.sort(key=len)

print(lst)
['Dan', 'dan', 'ram', 'Ronit']

So, in conclusion, the elements are ordered first case-insensitively, and then ordered by length. 因此,总而言之,元素首先不区分大小写地排序,然后按长度排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM