簡體   English   中英

如何將 Counter 對象轉換為可用的對列表?

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

我現在擁有的代碼:

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)])這對我沒有幫助......

提前致謝!

呃...

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

如果要按項目編號/字母升序排序:

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

你可以只使用sorted()

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

將計數器轉換為字典,然后將其溢出到兩個單獨的列表中,如下所示:

c=dict(c)
key=list(c.keys())
value=list(c.values())
>>>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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM