Python 3.x 根据频率按降序对列表进行排序
我有一个数字列表: [1, 2, 3, 1, 1, 2, 3, 1, 2, 3]. 我想按元素的频率对其进行排序,以得到以下结果: [1, 1, 1, 1, 3, 3, 3, 2, 2, 2]. 如果多个元素具有相同的频率,请按降序值对它们进行排序。你能找到办法吗。我使用上述方法,但得到的输出为:[1,1,1,2,2,2,3,3,3]Python 3.x 根据频率按降序对列表进行排序,python-3.x,Python 3.x,我有一个数字列表: [1, 2, 3, 1, 1, 2, 3, 1, 2, 3]. 我想按元素的频率对其进行排序,以得到以下结果: [1, 1, 1, 1, 3, 3, 3, 2, 2, 2]. 如果多个元素具有相同的频率,请按降序值对它们进行排序。你能找到办法吗。我使用上述方法,但得到的输出为:[1,1,1,2,2,2,3,3,3] from collections import Counter list = [1, 2, 3, 1, 1, 2, 3, 1, 2, 3] c = Coun
from collections import Counter
list = [1, 2, 3, 1, 1, 2, 3, 1, 2, 3]
c = Counter(list)
x = sorted(c.most_common(), key=lambda x: (-x[1], x[0]))
y = [([v] * n) for (v, n) in x]
z = sum(y, [])
print(z)
看起来您需要使用
reverse=True
Ex:
from collections import Counter
data = [1, 2, 3, 1, 1, 2, 3, 1, 2, 3]
c = Counter(data)
data.sort(key=lambda x: (c[x], x), reverse=True)
print(data)
[1, 1, 1, 1, 3, 3, 3, 2, 2, 2]
输出:
from collections import Counter
data = [1, 2, 3, 1, 1, 2, 3, 1, 2, 3]
c = Counter(data)
data.sort(key=lambda x: (c[x], x), reverse=True)
print(data)
[1, 1, 1, 1, 3, 3, 3, 2, 2, 2]
看起来您需要使用
reverse=True
Ex:
from collections import Counter
data = [1, 2, 3, 1, 1, 2, 3, 1, 2, 3]
c = Counter(data)
data.sort(key=lambda x: (c[x], x), reverse=True)
print(data)
[1, 1, 1, 1, 3, 3, 3, 2, 2, 2]
输出:
from collections import Counter
data = [1, 2, 3, 1, 1, 2, 3, 1, 2, 3]
c = Counter(data)
data.sort(key=lambda x: (c[x], x), reverse=True)
print(data)
[1, 1, 1, 1, 3, 3, 3, 2, 2, 2]
如果列表很长,您可能只需要对出现次数相同的项目进行排序:
from collections import Counter
from itertools import groupby
lst = [1, 2, 3, 1, 1, 2, 3, 1, 2, 3]
c = Counter(lst)
ret = []
for key, group in groupby(c.most_common(), key=lambda x: x[1]):
items = sorted((item for item, _ in group), reverse=True)
for item in items:
ret.extend(key * [item])
print(ret)
# [1, 1, 1, 1, 3, 3, 3, 2, 2, 2]
如果列表很长,您可能只需要对出现次数相同的项目进行排序:
from collections import Counter
from itertools import groupby
lst = [1, 2, 3, 1, 1, 2, 3, 1, 2, 3]
c = Counter(lst)
ret = []
for key, group in groupby(c.most_common(), key=lambda x: x[1]):
items = sorted((item for item, _ in group), reverse=True)
for item in items:
ret.extend(key * [item])
print(ret)
# [1, 1, 1, 1, 3, 3, 3, 2, 2, 2]