简体   繁体   中英

How can I get a count of repeated elements in a Python list?

I have to check how many number in a row a list has. Let's say:

list = [0, 0, 1, 1, 1, 0, 1, 0, 1, 1]

The output should look like this:

output_1 = 3 output_0 = 2

because we have 3 ones and 2 zeros in a row. How to do I this?

My code so far

from random import randint
x=int(input('number:'))
lista=[]
lista2=[]
lista3=[]
a=0

for i in range(0,x):
    a=randint(0,1)
    lista.append(a)



print('number of heads: ' , lista.count(1))
print('number of tails: ' , lista.count(0))


lista2=[]
def test(x):
    try:
        if lista[x] == lista[x+1]==0:
            lista2.append(x)
        else:
            return
    except IndexError:
        return

for i in range(len(lista)):
        test(i)

print(lista2)
print(lista)

for z in range(0,len(lista2)-1):
    if(lista2[z]+1==lista2[z+1]):
        lista3.append(1)
print(sum(lista3)+1)

There is a built-in function in python that can help you to count occurrences, count() . It takes one parameter which is the element you want to count their occurrence.

In your case, try to do like this:

output_1 = list.count(1)

You can use a data struture called dictionary to achieve it. I don't know python, here is the pseudocode.

// create a dictionary
dict = {}

// loop through all item in the given array, count all occurrence of each items
for num in list:
    if num in dict:
        dict[num] += 1
    else:
       // if number is not in the dictionary, push number as the key and the value 1 as its occurrence.
       dict[num] = 1

// loop through the dictionary, print the answer
for key in dict:
    print("output_" + key + " = " + dict[key])
data = [0, 0, 1, 1, 1, 0, 1, 0, 1, 1]
last = data[0]
count = 1
count_dict = {last:1}
if len(data) > 1:
    for x in data[1:]:
        if x == last:
            count +=1
            continue
        count_dict[last] = max(count_dict.get(last,0), count)
        count = 1
        last = x

If I understand correctly, the following will result in list of list of repeating numbers in a row. You can use it to get the length of list to get the count.

Result [[0, 0], [1, 1, 1], [1, 1]]

def flatten(iterable):
    try:
        for item in iterable:
            yield from flatten(item)
    except TypeError:
        yield iterable


listy = [0, 0, 1, 1, 1, 0, 1, 0, 1, 1]
listz = []
for i, j in enumerate(listy):
    listx = []
    if len(listy) == i+1 or len(listy) < i+1:
        next_item = None
    else:
        next_item = listy[i+1]
    if j == next_item:
        listx.append(j)
    else:
        pass
    listz.append(listx)

for i, j in enumerate(listz):
    if len(listz) == i+1 or len(listz) < i+1:
        pass
    else:
        if j and not listz[i+1]:
            a = j[0]
            j.append(a)

for i, j in enumerate(listz):
    if len(listz) == i+1 or len(listz) < i+1:
        pass
    else:
        if len(j) == 1 and listz[i+1][0] == j[0]:
            j.append(listz[i+1])
            listz[i] = list(flatten(j))
            listz[i+1] = []
final_list = [x for x in listz if x != []]

print(final_list)

Each time a zero or one appears, a counter increases. Every time each "i" value is different, append the value to an array and reset the counter. After each value has been appended, sort them and print the first value. Is this what you were looking for?

list = [0, 0, 1, 1, 1, 0, 1, 0, 1, 1]

output_1 = 0
output_2 = 0

zeroArray = []
oneArray = []
for i in list:

    if i == 0:
        if output_2 > 0:
            oneArray.append(output_2)
            output_2 = 0
        else:
            pass
        output_1 += 1

    elif i == 1:
        if output_1 > 0:
            zeroArray.append(output_1)
            output_1 = 0
        else:
            pass
        output_2 += 1

    else:
        pass
    
    
zeroArray.sort()
oneArray.sort()

print(list)

print("Highest 0 count:", zeroArray[-1])
print("Highest 1 count:", oneArray[-1])

Output:
Highest 0 count: 2
Highest 1 count: 3

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