Python Forum
Count elements in a list only if they are following each other and are similar
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Count elements in a list only if they are following each other and are similar
#1
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'))
Reply
#2
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.
Recommended Tutorials:
Reply
#3
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
Reply
#4
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.
Recommended Tutorials:
Reply
#5
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"))
Reply
#6
Thanks, let me try this
Reply
#7
(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 ??
Reply
#8
(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
Reply
#9
(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)
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#10
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']
Recommended Tutorials:
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  unable to remove all elements from list based on a condition sg_python 3 444 Jan-27-2024, 04:03 PM
Last Post: deanhystad
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 482 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  Function to count words in a list up to and including Sam Oldman45 15 6,603 Sep-08-2023, 01:10 PM
Last Post: Pedroski55
  Checking if a string contains all or any elements of a list k1llcod3 1 1,108 Jan-29-2023, 04:34 AM
Last Post: deanhystad
  Row Count and coloumn count Yegor123 4 1,331 Oct-18-2022, 03:52 AM
Last Post: Yegor123
  How to change the datatype of list elements? mHosseinDS86 9 2,001 Aug-24-2022, 05:26 PM
Last Post: deanhystad
  For Word, Count in List (Counts.Items()) new_coder_231013 6 2,610 Jul-21-2022, 02:51 PM
Last Post: new_coder_231013
  ValueError: Length mismatch: Expected axis has 8 elements, new values have 1 elements ilknurg 1 5,151 May-17-2022, 11:38 AM
Last Post: Larz60+
  How to get unique entries in a list and the count of occurrence james2009 5 2,992 May-08-2022, 04:34 AM
Last Post: ndc85430
  Why am I getting list elements < 0 ? Mark17 8 3,158 Aug-26-2021, 09:31 AM
Last Post: naughtyCat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020