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...
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()
:
>>> 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.