【发布时间】:2015-11-17 00:23:25
【问题描述】:
排序键 Lambda 参数
我不明白 lambda 参数是如何工作的,[-e[0],e[1]] 部分特别令人困惑。我已经删除了所有多余的打印代码,并且我还从我的问题中删除了所有不必要的代码。参数-e[0]实现了什么,e[1]实现了什么?
data.sort(key = lambda e: [-e[0],e[1]]) # --> anonymous function
print ("This is the data sort after the lambda filter but NOT -e %s" %data)`
[in] 'aeeccccbbbbwwzzzwww'
[out] This is the data before the sort [[2, 'e'], [4, 'c'], [1, 'a'], [4, 'b'], [5, 'w'], [3, 'z']]
[out] This is the data sort before the lambda filter [[1, 'a'], [2, 'e'], [3, 'z'], [4, 'b'], [4, 'c'], [5, 'w']]
[out] This is the data sort after the lambda filter but NOT -e [[1, 'a'], [2, 'e'], [3, 'z'], [4, 'b'], [4, 'c'], [5, 'w']]
[out] This is the data sort after the lambda filter [[5, 'w'], [4, 'b'], [4, 'c'], [3, 'z'], [2, 'e'], [1, 'a']]
[out] w 5
[out] b 4
[out] c 4
【问题讨论】:
-
-e[0]是-1 * (the_first_element_in_e),即对于e == [2, 'e'],它将是-2。究竟是什么让您感到困惑? -
-2如何帮助我们对键和值进行排名?我们正在尝试创建一个程序,以降序显示单词出现的次数。 -
乘以 -1 意味着它们将首先排序,而不是通常的最低排序。删除
-看看有什么变化。 -
哦,它只会颠倒排序函数的顺序,但不会将任何值变为负数?哦,我明白了。此外,我们必须创建一个 lambda 函数来遍历列表索引。
-
您正在创建一个新对象进行排序,而不是更改原始对象。这是一个问题吗?
标签: python sorting dictionary lambda key