简体   繁体   English

如何将 Counter 对象转换为可用的对列表?

[英]How to convert a Counter object into a usable list of pairs?

The code I have now:我现在拥有的代码:

from collections import Counter
c=Counter(list_of_values)

returns:返回:

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

I want to sort this list into numeric(/alphabetic) order by item, not number of occurrences.我想将此列表按项目排序为数字(/字母)顺序,而不是出现次数。 How can I convert this into a list of pairs such as:如何将其转换为对列表,例如:

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

Note: If I use c.items(), I get: dict_items([('1', 2), ('3', 2), ('2', 4), ('5', 5)]) which does not help me...注意:如果我使用 c.items(),我得到:dict_items([('1', 2), ('3', 2), ('2', 4), ('5', 5)])这对我没有帮助......

Thanks in advance!提前致谢!

Err...呃...

>>> list(collections.Counter(('5', '5', '4', '5')).items())
[('5', 3), ('4', 1)]

If you want to sort by item numberic/alphabetically ascending:如果要按项目编号/字母升序排序:

l = []
for key in sorted(c.iterkeys()):
    l.append([key, c[key]])

You can just use sorted() :你可以只使用sorted()

>>> c
Counter({'5': 5, '2': 4, '1': 2, '3': 2})
>>> sorted(c.iteritems())
[('1', 2), ('2', 4), ('3', 2), ('5', 5)]

Convert the counter to a dictionary and then spilt it into two separate lists like this:将计数器转换为字典,然后将其溢出到两个单独的列表中,如下所示:

c=dict(c)
key=list(c.keys())
value=list(c.values())
>>>RandList = np.random.randint(0, 10, (25))
>>>print Counter(RandList)

outputs something like...输出类似...

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

And with this...有了这个...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM