0

Possible Duplicate:
How do you split a list into evenly sized chunks in Python?

Basically, I have a list, and I am iterating through every odd numbered index in the list. What I want to do, is based on the value of each odd numbered index, to then update a variable with the value in the even numbered index directly after said odd numbered index.

So if lst[1] contains the value p, then I want the value of x to be the value at lst[2]: x = lst[2].

If lst[3] contains the value m then I want y to be the value at lst[4]: y = lst[4]

The length of the list is never set in stone, since it grabs it from a file.

I am currently iterating through the list using this code:

for item in lst:
    if lst[range(1, len(lst), 2] == "p"
        x = ??

EDIT: I suppose to be more specific, I have created a class, and now am creating a function that will take information from a file, and use it to fill in the methods in my class. To do so I am reading in the file using readlines and then going through that list created by readlines and updating the methods in my class depending on what is in the file. Every odd line in the file is an indicator of which method I need to update with the line that comes directly after.

So:

if lst[1] == "p":
   s.methodOne(lst[2])
if lst[1] == "m":
    s.methodTwo(lst[2])

I'm just not sure how to grab what is in the even indexes after my odd ones.

My code is probably not very neat, but here is what I have so far:

def processScores(fname):
    infile = open(fname, 'r')
    lineinfo = infile.readlines()
    infile.close()
    lstinfo = []
    for item in lineinfo:
        lst = item.split(",")
        s = Score()
        s.initialize(lst[0])
        if lst[range(1, len(lst -1), 2] == "o" or "O":
Community
  • 1
  • 1
Daniel Love Jr
  • 950
  • 5
  • 13
  • 17

2 Answers2

2
for idx in xrange(1, len(lst), 2):
    if lst[idx] == 'p':
        ...
    if lst[idx] == 'm':
        ...

Note that the first element of lst is lst[0], so you are skipping it altogether here

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
0

I like itertools:

from itertools import izip

def grouper(n, iterable):
    args = [iter(iterable)] * n
    return izip(*args)

line = 'hello, my name is really not pete.'
#              ^^                    ^^

for a, b in grouper(2, line[1:]):
    if a == 'm':
        print b
    elif a == 'p':
        print b

Result:

$ python oddeven.py
y
e
pillmuncher
  • 10,094
  • 2
  • 35
  • 33