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
#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


Messages In This Thread
RE: Count elements in a list only if they are following each other and are similar - by cvsae - Aug-01-2019, 10:23 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  unable to remove all elements from list based on a condition sg_python 3 485 Jan-27-2024, 04:03 PM
Last Post: deanhystad
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 509 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  Function to count words in a list up to and including Sam Oldman45 15 6,749 Sep-08-2023, 01:10 PM
Last Post: Pedroski55
  Checking if a string contains all or any elements of a list k1llcod3 1 1,144 Jan-29-2023, 04:34 AM
Last Post: deanhystad
  Row Count and coloumn count Yegor123 4 1,374 Oct-18-2022, 03:52 AM
Last Post: Yegor123
  How to change the datatype of list elements? mHosseinDS86 9 2,043 Aug-24-2022, 05:26 PM
Last Post: deanhystad
  For Word, Count in List (Counts.Items()) new_coder_231013 6 2,668 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,226 May-17-2022, 11:38 AM
Last Post: Larz60+
  How to get unique entries in a list and the count of occurrence james2009 5 3,026 May-08-2022, 04:34 AM
Last Post: ndc85430
  Why am I getting list elements < 0 ? Mark17 8 3,201 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