J. P.
J. P.

Reputation: 299

Python: Reading n lines at a time in a list

I'm new to python so I know there has to be a more elegant way to do this and was hoping to get some advice on this.

Currently, I have a list that consists of x entries. I want to:

Right now, I'm going very primitive and just doing something like:

first = mylist[0:11]
mean = sum(first)/nentries
second = mylist{11:22]
mean2 = sum(second)/nentries
...

As you can see, this is extremely novice and not elegant at all if I have say 352 entries and I need to read 11 lines at a time from them. Is there an easy way to loop over the list and only pick out n entries (in this case, 11) at a time? Thanks!

Upvotes: 0

Views: 565

Answers (1)

squid
squid

Reputation: 2615

why not using range:

range(start, stop[, step]) -> list of integers

In your case:

for start in range(0,len(mylist), 11):
    end = start + 11
    blablabla

or itertools.count:

range(start, stop[, step]) -> list of integers

Upvotes: 1

Related Questions