Home > Blockchain >  Loop through a list with itertools.islice
Loop through a list with itertools.islice

Time:11-01

I'm trying to check the first 5 elements in a list, see if two or more are greater or equal to 5, and then check the next 5 elements with the same process.

I have this working by creating a new list and appending the next 5 elements:

from itertools import islice

myList = [3, 7, 3, 1, 2, 3, 6, 75, 77, 4]
print(sum(i>5 for i in islice(myList, 5)) >= 2)
newlist = myList[5:]
print(sum(i>5 for i in islice(newlist, 5)) >= 2)

Is there a way to loop through the original list, checking 5 elements at a time without creating a new list?

Thanks in advance.

CodePudding user response:

You can just use a range with step 5

myList = [3, 7, 3, 1, 2, 3, 6, 75, 77, 4]

for i in range(0, len(myList), 5):
    if sum(v > 5 for v in myList[i:i 5]) > 1:
        print(f'Chunk {i}->{i 5} has two or more values greater than 5')

Output:

Chunk 5->10 has two or more values greater than 5
  • Related