根据计数器值对列表进行排序

时间:2018-04-08 23:32:36

标签: python python-3.x

如何根据Counter对象的值对python列表进行排序?

c = Counter({"a": 1, "b": 6, "c":19})
l = ["b", "c", "a"]

# after sorting based on counter values
l = ["c", "b", "a"]

2 个答案:

答案 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>