简体   繁体   English

对此 lambda function 的一些解释

[英]Some explanation for this lambda function

Trying to get my head around how the expression below is evaluated, looking at the returned list:试图了解如何评估下面的表达式,查看返回的列表:

sorted([1, 2, 3, 4, 5, 6, 7, 8, 9], key=lambda x: abs(2-x))

which gives:这使:

[2, 1, 3, 4, 5, 6, 7, 8, 9]

I'm not sure what value x in abs(2-x) takes.我不确定abs(2-x) x的 x 取什么值。 Is it the list elements' position [0,1,2,..,8] or the actual elements' values [1,2,3,.,9]是列表元素的 position [0,1,2,..,8]还是实际元素的值[1,2,3,.,9]

Can someone explain?有人可以解释吗?

It's the values that are passed to the lambda and it returns the new 'keys' to be used for sorting.它是传递给 lambda 的值,它返回用于排序的新“键”。

In this case the lambda will return [1, 0, 1, 2, 3, 4, 5, 6, 7] so the value 2 with the key 0 will move to the front, followed by 1 and 3, which both have index 1, and then the rest of the values.在这种情况下,lambda 将返回 [1, 0, 1, 2, 3, 4, 5, 6, 7] 因此键为 0 的值 2 将移到前面,然后是 1 和 3,它们都有索引1、然后是rest的数值。

x is the actual element. x是实际元素。

when writing:写作时:

key=lambda x: abs(2-x)

its exactly such as:它完全如:

def sort_key(x):
  return abs(2 - x)

but only the body of the function is passed to key when writing key=lambda x: abs(2-x) .但是在编写key=lambda x: abs(2-x)时,只有 function 的主体被传递给key

list:列表:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

its sorted positions are influenced by the result of key when calling that lambda .调用lambda时,其排序位置受key结果的影响。

the actual sort:实际排序:

1 -> abs(2 - 1) = (1) [position]
2 -> abs(2 - 2) = (0) [position]
3 -> abs(2 - 3) = (1) [position]
4 -> abs(2 - 4) = (2) [position]
5 -> abs(2 - 5) = (3) [position]
6 -> abs(2 - 6) = (4) [position]
7 -> abs(2 - 7) = (5) [position]
8 -> abs(2 - 8) = (6) [position]
9 -> abs(2 - 9) = (7) [position]

explanation:解释:

  • element 1 is giving 1 so its positioned on index 1元素1给出1 ,因此它位于索引1
  • element 2 is giving 0 so its positioned on index 0元素2给出0 ,因此它位于索引0
  • element 3 is giving 1 so its positioned on index 1 , but 1 is already occupied, so its positioned next to element on pos 1元素3给出1 ,因此它位于索引1上,但1已被占用,因此它位于 pos 1上的元素旁边
  • element 4 is giving 2 so its positioned on index 2元素4给出2 ,因此它位于索引2

.... ……

and so on.等等。

First: Python's built-in sorted function has the signature:第一:Python内置的sorted function有签名:

sorted(iterable, *, key=None, reverse=False)

meaning if a value is passed to the key parameter, sorted will sort the iterable according to the value of key .这意味着如果将值传递给key参数, sorted将根据key的值对iterable进行排序。

Second: in this case key takes a function (lambda) and evaluates it.第二:在这种情况下, key采用 function (lambda) 并对其进行评估。 The result of the evaluation is as in @alexzander's answer [1,0,1,2,3..7] .评估结果如@alexzander 的回答[1,0,1,2,3..7]中所述。 sorted use this as the key to sort the given list in that order (ascending, assuming reverse=False which is the default). sorted使用它作为key以按该顺序对给定列表进行排序(升序,假设reverse=False这是默认值)。

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

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