Python 基于计数器值的排序列表
如何根据计数器对象的值对python列表进行排序Python 基于计数器值的排序列表,python,python-3.x,Python,Python 3.x,如何根据计数器对象的值对python列表进行排序 c = Counter({"a": 1, "b": 6, "c":19}) l = ["b", "c", "a"] # after sorting based on counter values l = ["c", "b", "a"] 采用如下关键函数: 代码: 或作为: l.sort(key=lambda x: -c[x]) 测试代码: 结果: 使用计数器本身的最常用的方法,而不是排序,可以获得相同的结果 most_common = Co
c = Counter({"a": 1, "b": 6, "c":19})
l = ["b", "c", "a"]
# after sorting based on counter values
l = ["c", "b", "a"]
采用如下关键函数:
代码:
或作为:
l.sort(key=lambda x: -c[x])
测试代码:
结果:
使用计数器本身的
最常用的方法,而不是排序
,可以获得相同的结果
most_common = Counter({"a": 1, "b": 6, "c":19}).most_common()
列表理解:
most_common = [item[0] for item in most_common]
import operator
most_common = list(map(operator.itemgetter(0), most_common))
['c', 'b', 'a']
操作员:
most_common = [item[0] for item in most_common]
import operator
most_common = list(map(operator.itemgetter(0), most_common))
['c', 'b', 'a']
结果:
most_common = [item[0] for item in most_common]
import operator
most_common = list(map(operator.itemgetter(0), most_common))
['c', 'b', 'a']
可能重复的结果不应该被逆转吗?