【问题标题】:Please explain how does the second line of code works请解释第二行代码是如何工作的
【发布时间】:2020-12-14 15:03:29
【问题描述】:

请解释第二行代码。

代码:

s_counter = collections.Counter(s).most_common()
s_counter = sorted(s_counter, key=lambda x: (x[1] * -1, x[0]))

【问题讨论】:

标签: python


【解决方案1】:

考虑:

import collections

s = [2, 2, 2, 3, 4, 4, 1, 1]
s_counter = collections.Counter(s).most_common()

这给了

[(2, 3), (4, 2), (1, 2), (3, 1)]

请注意,在结果中,(4, 2) 出现在 (1, 2) 之前,因为数组中 4 出现在 1 之前。

显然,代码的作者希望同时按频率和值对结果进行排序。为此,他将排序键定义为lambda x: (x[1] * -1, x[0])。给定 (value, frequency) 的元组,这将首先按 x[1](频率)排序;乘以 -1 使其成为降序排序。次要排序标准是值本身。这将是升序排序。因此,结果是:

[(2, 3), (1, 2), (4, 2), (3, 1)]

【讨论】:

    猜你喜欢
    • 2017-08-08
    • 2012-08-13
    • 2018-12-24
    • 1970-01-01
    • 1970-01-01
    • 2012-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多