简体   繁体   English

在 sorted 方法中使用 if else f'y{x}' 评估 lambda function

[英]Evaluating a lambda function with if else f'y{x}' inside the sorted method

I have the following sorting problem:我有以下排序问题:

Given a list of strings, return the list of strings sorted, but group all strings starting with 'x' first.给定一个字符串列表,返回排序后的字符串列表,但首先将所有以“x”开头的字符串分组。

Example: ['mix', 'banana','xyz', 'apple', 'xanadu', 'aardvark'] Will return: ['xanadu', 'xyz', 'aardvark', 'apple', 'banana','mix']示例: ['mix', 'banana','xyz', 'apple', 'xanadu', 'aardvark'] 将返回: ['xanadu', 'xyz', 'aardvark', 'apple', 'banana' ,'混合']

I solved by splitting the list into 2:我通过将列表拆分为 2 来解决:

def front_x(words):

    return [w for w in words if w[0] == "x"] + [w for w in words if w[0] != "x"]

Another pythonic solution for this problem would be using sorted method, like this:这个问题的另一个pythonic解决方案是使用sorted方法,如下所示:

def front_x(words):

    return sorted(words, key=lambda x: x if x[0] == 'x' else f'y{x}')

I am having a hard time to understand what is going on after else .我很难理解else之后发生了什么。 Any good soul to help me out?有好心人帮帮我吗? I'm grateful.我很感激。

return sorted(words, key=lambda x: x if x[0] == 'x' else f'y{x}')

Translation:翻译:

"Return a sorted version of words . For each item x in words , use x for comparison when sorting, but only if x[0] is equal to the character 'x' . Otherwise, append 'y' to the front of x and use that for comparison instead" "返回words的排序版本。对于words中的每个项目x ,排序时使用x进行比较,但前提是x[0]等于字符'x' 。否则,append 'y'x的前面和用它来比较”

The f'y{x}' syntax is the f-string syntax . f'y{x}'语法是f-string 语法 It's equivalent to:它相当于:

"y" + str(x)

There are plenty of other equivalent ways to insert a character into a string.还有很多其他等效的方法可以将字符插入字符串。 That's just how it's being done here.这就是这里的做法。

So, if your word list was:所以,如果你的单词列表是:

aardvark
xylophone
xamarin
xenophobia
zipper
apple
bagel
yams

The list would be sorted as if it contained the following:该列表将被排序,就好像它包含以下内容:

yaardvark
xylophone
xamarin
xenophobia
yzipper
yapple
ybagel
yyams

And therefore the output would be:因此 output 将是:

xamarin
xenophobia
xylophone
aardvark
apple
bagel
yams
zipper

So, what is happening is that, when the list is sorted, items that start with 'x' will always appear before any other items.因此,发生的情况是,当列表排序时,以'x'开头的项目将始终出现在任何其他项目之前。

f'y{x}' in an f-string expression that prepends the character 'y' to the original string ( x ). f'y{x}'在将字符'y'附加到原始字符串 ( x ) 的f 字符串表达式中。 That way, all items that don't start with 'x' will sort as if they started with 'y' , which puts them after all of the items that do start with 'x' .这样,所有不以'x'开头的项目都将按照以'y'开头的方式进行排序这会将它们放在所有以'x'开头的项目之后。

For example, 'banana' will be sorted as if it was 'ybanana' , which naturally places it after 'xyz' .例如, 'banana'将被排序'ybanana' ,自然将其放在'xyz'之后。

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

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