I have a list: list = [A, B, C, D, A, A, A, B, E, C, C, E, D, A, B]
I want to count appearance of every element, so I can use function count
. But I want to create a table which contains a tuple (element, number_of_reps)
, it is: [(A, 5), (B, 3), (C, 3), (D, 2), (E, 2)].
I wanted to make it as:
newlist = []
for i in list:
rep = list.count(i)
tup = (i, rep)
if tup not in newlist:
newlist.append(tup)
But can I do it better: faster or using any built in function?
Use collections.Counter
. It has a most_common
method which does exactly what you want...
>>> import collections
>>> A, B, C, D, E = 'ABCDE'
>>> lst = [A, B, C, D, A, A, A, B, E, C, C, E, D, A, B]
>>> collections.Counter(lst).most_common()
[('A', 5), ('C', 3), ('B', 3), ('E', 2), ('D', 2)]
The Counter is a dictionary which holds a mapping of the keys to the number of times that key was seen in the input iterable.
>>> collections.Counter(lst)
Counter({'A': 5, 'C': 3, 'B': 3, 'E': 2, 'D': 2})
most_common
is just a simple method to get a handle on the N
most common elements in the input -- with no arguments, it just sorts the items by the number of counts.
Use collections.Counter
. The interface is similar to that of a dictionary, and you can call most_common
to give exactly the output you want:
>>> import collections
>>> some_list = ["A", "B", "C", "D", "A", "A", "A", "B", "E", "C", "C", "E", "D", "A", "B"]
>>> counter = collections.Counter(some_list)
>>> counter.most_common()
[('A', 5), ('C', 3), ('B', 3), ('E', 2), ('D', 2)]
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.