简体   繁体   中英

Counting identical list-elements in a row in Python

I am using Python3. I have a list a of only integers. Now, I want to save the element and the number it repeats itself in a row in another list.

Example:

a = [6, 0, 0, 2, 2, 2, 2, 1, 89, 89]

Output:

result = ["6,1", "0, 2", "2, 4", "1, 1", "89, 2"]    
# the number before the "," represents the element, the number after the "," represents how many times it repeats itself.

How to efficiently achieve my goal?

I believe all the solutions given are counting the total occurrences of a number in the list rather than counting the repeating runs of a number.

Here is a solution using groupby from itertools. It gathers the runs and appends them to a dictionary keyed by the number.

from itertools import groupby

a = [6, 0, 0, 2, 2, 2, 2, 1, 89, 89]
d = dict()

for k, v in groupby(a):
    d.setdefault(k, []).append(len(list(v)))

Dictionary created:

>>> d
{6: [1], 0: [2], 2: [4], 1: [1], 89: [2]}

Note that all runs only had 1 count in their list. If there where other occurrences of a number already seen, there would be multiple counts in the lists (that are the values for dictionary).

for counting an individual element, us list.count ,

ie, here, for, say 2 , we user a.count(2) , which outputs 4 ,

also, set(a) gives the unique elements in a

overall answer,

a = [6, 0, 0, 2, 2, 2, 2, 1, 89, 89]
nums = set(a)
result = [f"{val}, {a.count(val)}" for val in set(a)]
print(result)

which gives

['0, 2', '1, 1', '2, 4', '6, 1', '89, 2']

Method 1: using for loop

a = [6, 0, 0, 2, 2, 2, 2, 1, 89, 89]
result = []
a_set = set(a) # transform the list into a set to have unique integer
for nbr in a_set:
    nbr_count = a.count(nbr)
    result.append("{},{}".format(nbr, nbr_count))

print(result) # ['0,2', '1,1', '2,4', '6,1', '89,2']

Method 2: using list-comprehensions

result = ["{},{}".format(item, a.count(item)) for item in set(a)]
print(result) # ['0,2', '1,1', '2,4', '6,1', '89,2']

you can use Python List count() Method, method returns the number of elements with the specified value.

a = [6, 0, 0, 2, 2, 2, 2, 1, 89, 89]

print ({x:a.count(x) for x in a})

output:

{6: 1, 0: 2, 2: 4, 1: 1, 89: 2}
a = [6, 0, 0, 2, 2, 2, 2, 1, 89, 89]
dic = dict()
for i in a:
     if(i in dic):
             dic[i] = dic[i] + 1
     else:
             dic[i] = 1

result = []
for i in dic:
     result.append(str(i) +"," + str(dic[i]))

Or:

from collections import Counter
a = [6, 0, 0, 2, 2, 2, 2, 1, 89, 89]
mylist = [Counter(a)]
print(mylist)

You can use Counter from collections:

from collections import Counter
a = [6, 0, 0, 2, 2, 2, 2, 1, 89, 89]
counter = Counter(a)    
result = ['{},{}'.format(k, v) for k,v in counter.items()]

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.

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