简体   繁体   English

Python 已排序 lambda function 返回 boolean

[英]Python sorted lambda function returning a boolean

So, I have a list of names, and I'm trying to sort the list such that the names that start with a vowel are positioned first within the list and then those that don't start with a vowel are then positioned after them and sorted alphabetically.所以,我有一个名字列表,我正在尝试对列表进行排序,使以元音开头的名字在列表中排在第一位,然后将不以元音开头的名字排在它们之后,然后按字母顺序排序。

To do this, I wrote the following code, however, the result is not what I expected:为此,我编写了以下代码,但是结果不是我所期望的:

a = ["anna", "ollie", "tim", "bob", "trevor", "susan"]
print(sorted(a, key=lambda x: (x[0] in 'aeiou', x)))

Outcome:结果:

['bob', 'susan', 'tim', 'trevor', 'anna', 'ollie']

I thought based on my code, the names: "anna" and "ollie" should be positioned first, and then the rest of the names since these two names would return true for the first part of my lambda function.我认为根据我的代码,名字:“anna”和“ollie”应该放在第一位,然后是名字的 rest,因为这两个名字对于我的 lambda function 的第一部分将返回 true。

I'd appreciate it if someone can explain why I'm getting this result and what I need to do in order to get my desired outcome.如果有人能解释为什么我会得到这个结果以及我需要做什么才能得到我想要的结果,我将不胜感激。

Thanks!!谢谢!!

The reason is that:原因是:

x[0] in 'aeiou' 

returns 1 (or True) for ['anna', 'ollie'] and 0 (or False) for the rest. So 0 < 1, hence the output.['anna', 'ollie']返回 1(或 True),为 rest 返回 0(或 False)。因此 0 < 1,因此为 output。

Do this instead:改为这样做:

print(sorted(a, key=lambda x: (x[0] not in 'aeiou', x)))

Output Output

['anna', 'ollie', 'bob', 'susan', 'tim', 'trevor']

For an explanation in comparisons, check the documentation , the quote below is from there:有关比较的解释,请查看 文档,下面的引述来自那里:

Tuples and lists are compared lexicographically using comparison of corresponding elements.元组和列表使用相应元素的比较按字典顺序进行比较。 This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.这意味着要比较相等,每个元素必须比较相等,并且两个序列必须具有相同的类型和相同的长度。

Also for the behavior of Boolean values I suggest, the following link , quoting:同样对于 Boolean 值的行为,我建议,以下 链接,引用:

Boolean values are the two constant objects False and True. Boolean 值是两个常量对象 False 和 True。 They are used to represent truth values (although other values can also be considered false or true).它们用于表示真值(尽管其他值也可以被认为是假或真)。 In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively.在数字上下文中(例如用作算术运算符的参数时),它们的行为分别类似于整数 0 和 1。

When you are returning a boolean value, in python it corresponds True == 1 , False == 0 .当您返回 boolean 值时,在 python 中它对应True == 1False == 0 So now when you sort your array, 0 is less than 1. That's why your are getting "anna" and "ollie" positioned last and rest of the names first.所以现在当你对你的数组进行排序时,0 小于 1。这就是为什么你将“anna”和“ollie”放在最后,而 rest 的名字放在前面。

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

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