Home > database >  Count the elements before a certain index in a list in Python
Count the elements before a certain index in a list in Python

Time:09-13

Here is a demo list. It is a list of strings:

list_one = ['3', '5', '6', 'Week 1', '11', '12', '13', 'Week 2', '279']

Here is my code:

counts = []
for num, i in enumerate(list_one):
    if "Week" in i:
        counts.append(num)
        num = 0
        
print(counts)

Instead of the output [3, 7], I'd like to get [3, 3]

I don't want to count any element that has already been counted and to exclude countings weeks themselves. In my head, I'm imagining resetting the num back to 0 after every occurrence of 'Week' in order to accomplish this but it isn't working.

CodePudding user response:

list_one = ['3', '5', '6', 'Week 1', '11', '12', '13', 'Week 2', '279']
count = 0
counts = []
for element in list_one:
    if "Week" in element:
        counts.append(count)
        count = 0
    else:
        count  = 1
print(counts)

CodePudding user response:

The enumarate actually gives

[(0, '3') (1, '5') (2, '6') (3, 'Week 1') (4, '11') (5, '12') (6, '13') (7, 'Week 2') (8, '279')]

when you iterate through above with two variables(num, i), when you make num to 0, it only applies for present iteration. It changes in next iteration

list_one = ['3', '5', '6', 'Week 1', '11', '12', '13', 'Week 2', '279']
counts = []
num = 0
for i in list_one:
    if "Week" in i:
        counts.append(num)
        num = 0
    else:
        num  = 1
print(counts)

check the above code

  • Related