Python Forum

Full Version: Count elements in a list only if they are following each other and are similar
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Hello friends, i have this code which counts number of apple in the fruit list, it returns 6 which is correct.
How can i tell python to count a fruit only if the next fruit is similar to the previous fruit and ignore others
where the previous fruit ain't similar.
So that in this case i get the count as 3 (i.e the 3 apple between lemon and banana in the list)



fruits=['mango','orange','apple','lemon','apple','apple','apple','banana','avocado','apple','mango','pineapple','orange','apple']
print(fruits.count('apple'))
You can loop the list, keeping track of the element, count, and position. Then whenever another one exceeds that count it replaces it. Then you have the element, its count, and positions of what you are looking for.
How do i do that? i don't have a lot of experience in python any documentation to use as a road-map will be highly appreciated
for loops

enumerate for index with for loops

then keep the current info in a variable, dictionary, or even class to compare and change as your looping to get the latest result.
try this
fruits=['mango','orange','apple','lemon','apple','apple','apple','banana','avocado','apple','mango','pineapple','orange','apple']



def countFruit(fruit):
    for x in range(0, len(fruits) -1):
        prevFruit = None
        if x > 0: prevFruit = fruits[x -1]

        thisFruit = fruits[x]
        nextFruit = fruits[x +1]

        if fruit == nextFruit and fruit == prevFruit:
            return fruits.count(fruit)

print (countFruit("apple"))
Thanks, let me try this
(Aug-01-2019, 10:24 PM)law Wrote: [ -> ]Thanks, let me try this
can you give me an example want do you want as result ??
(Aug-01-2019, 10:30 PM)cvsae Wrote: [ -> ]
(Aug-01-2019, 10:24 PM)law Wrote: [ -> ]Thanks, let me try this
can you give me an example want do you want as result ??

I want python to count only if the fruits are similar and consecutive.
in this case the count should be 3 (it should only count the 'apple','apple','apple' in the code since they are similar and consecutive. It should ignore the other apple since there is no similar consecutive element
(Aug-01-2019, 10:58 PM)law Wrote: [ -> ]I want python to count only if the fruits are similar and consecutive.

Do you want count only one specific item in list? What should happen if there are several consecutive groups of 'apple'?

>>> fruits = ['apple', 'apple', 'apple', 'mango', 'apple', 'apple']
It is good practice to stick PEP8 naming conventions. So countFruit --> count_fruit, prevFruit --> prev_fruit etc


There is built-in module itertools where is groupby() for grouping.

I would extract all groups which contain required item, count how many items in every group and find maximum (this is not handling situations where item is missing):

def max_consecutive(item, items=fruits):
    return max(sum(1 for _ in group) for status, group in groupby(items, key=lambda x:x == item) if status == True)
Just posting the full code of the above post in case you didnt know it was in itertools. as well as added if there was more than one count.

from itertools import groupby

fruits=['mango','orange','orange','orange', 'apple','lemon','apple','apple','apple','banana','avocado','apple','mango','pineapple','orange','apple']

def max_consecutive(item, items=fruits):
    return max(sum(1 for _ in group) for status, group in groupby(items, key=lambda x:x == item) if status == True)

d = {}
for item in fruits:
    num = max_consecutive(item, fruits)
    d[item] = num
    
highest = max(d.values())
print(highest)
print([k for k, v in d.items() if v == highest])
Output:
3 ['orange', 'apple']
Pages: 1 2