12

我现在拥有的代码:

from collections import Counter
c=Counter(list_of_values)

返回:

Counter({'5': 5, '2': 4, '1': 2, '3': 2})

我想按项目将此列表排序为数字(/字母)顺序,而不是出现次数。如何将其转换为对列表,例如:

[['5',5],['2',4],['1',2],['3',2]]

注意:如果我使用 c.items(),我会得到:dict_items([('1', 2), ('3', 2), ('2', 4), ('5', 5)])这对我没有帮助...

提前致谢!

4

5 回答 5

19

呃...

>>> list(collections.Counter(('5', '5', '4', '5')).items())
[('5', 3), ('4', 1)]
于 2012-06-15T18:02:57.947 回答
1

如果要按项目编号/字母升序排序:

l = []
for key in sorted(c.iterkeys()):
    l.append([key, c[key]])
于 2012-06-15T18:38:27.000 回答
1

您可以使用sorted()

>>> c
Counter({'5': 5, '2': 4, '1': 2, '3': 2})
>>> sorted(c.iteritems())
[('1', 2), ('2', 4), ('3', 2), ('5', 5)]
于 2012-06-15T18:42:47.983 回答
0

将计数器转换为字典,然后将其拆分为两个单独的列表,如下所示:

c=dict(c)
key=list(c.keys())
value=list(c.values())
于 2019-07-10T10:30:22.260 回答
-3
>>>RandList = np.random.randint(0, 10, (25))
>>>print Counter(RandList)

输出类似...

Counter({1: 5, 2: 4, 6: 4, 7: 3, 0: 2, 3: 2, 4: 2, 5: 2, 9: 1})

有了这个...

>>>thislist = Counter(RandList)
>>>thislist = thislist.most_common()
>>>print thislist
[(1, 5), (2, 4), (6, 4), (7, 3), (0, 2), (3, 2), (4, 2), (5, 2), (9, 1)]
>>>print thislist[0][0], thislist[0][1]
1 5
于 2016-05-27T22:10:10.327 回答