如何根据Counter对象的值对python列表进行排序?
c = Counter({"a": 1, "b": 6, "c":19})
l = ["b", "c", "a"]
# after sorting based on counter values
l = ["c", "b", "a"]
答案 0 :(得分:1)
sorted()
采用了以下关键功能:
sorted(l, key=lambda x: -c[x])
或就地:
l.sort(key=lambda x: -c[x])
from collections import Counter
c = Counter({"a": 1, "b": 6, "c": 19})
l = ["b", "c", "a"]
# after sorting based on counter values
l = ["c", "b", "a"]
print(sorted(l, key=lambda x: -c[x]))
['c', 'b', 'a']
答案 1 :(得分:1)
使用来自Counter本身的sorted
方法,您可以取代most_common
而不是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']
<强>结果:强>
<mat-select placeholder="item" [(ngModel)]="selectedItem" [formControl]="selectedItem[ix]" required
(ngModelChange)="allowCheck(ix, checkBox)">
<mat-option *ngFor="let item of allItems()" [value]="item">
{{ item }}
</mat-option>
</mat-select>
<mat-checkbox [(ngModel)]="checkMe" #checkBox>
</mat-checkbox>