Python - 按 K 的频率对行进行排序
pythonserver side programmingprogramming更新于 2025/11/1 16:44:17
当需要按‘K’的频率对行进行排序时,可以使用列表推导和‘计数器’方法。
示例
下面是相同的演示
from collections import Counter
my_list = [34, 56, 78, 99, 99, 99, 99, 99, 12, 12, 32, 51, 15, 11, 0, 0]
print ("列表是 ")
print(my_list)
my_result = [item for items, c in Counter(my_list).most_common() for item in [items] * c]
print("结果为 ")
print(my_result)
输出
列表是 [34, 56, 78, 99, 99, 99, 99, 99, 12, 12, 32, 51, 15, 11, 0, 0] 结果是 [99, 99, 99, 99, 99, 0, 0, 12, 12, 32, 34, 11, 78, 15, 51, 56]
解释
将所需的包导入到环境中。
定义一个列表并显示在控制台上。
使用列表推导式对元素进行迭代,并且"most_Common"方法用于所有元素。
这将转换为列表。
这将分配给变量。
结果显示在控制台上。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

