Iterate through a list of 3

a = [3,5,8,3,9,5,0,3,2,7,5,4] for o in a[::3]: print o 

This gives me the first and every 3 points. 3,3,0,7

Is there a way to get the following two items?

 a = [3,5,8,3,9,5,0,3,2,7,5,4] for o in a[::3]: if o == 0: print o print o + 1 print o + 2 

output 0 3 2

I know this is wrong, but maybe you can see what I'm trying to do. Basically, I have a long list of properties, and there are three parts to each property, parent_id, property_type and property_value, and I need to extract all three parts of the property from the list.

+4
source share
6 answers

You can do this using the "grouper" recipe from the itertools documentation :

 def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args) 

Example:

 >>> a = [3, 5, 8, 3, 9, 5, 0, 3, 2, 7, 5, 4] >>> list(grouper(3, a)) [(3, 5, 8), (3, 9, 5), (0, 3, 2), (7, 5, 4)] 
+14
source
 >>> a = [3,5,8,3,9,5,0,3,2,7,5,4] >>> for pos in xrange(0, len(a), 3): ... print a[pos:pos+3] ... [3, 5, 8] [3, 9, 5] [0, 3, 2] [7, 5, 4] >>> 
+2
source

Not very pythonic, but you can use:

 for i in range(0, len(a), 3): print a[i] print a[i+1] print a[i+2] 
+2
source

Try the following:

 array = [3,5,8,3,9,5,0,3,2,7,5,4] for i in xrange(0, len(array), 3): a, b, c = array[i:i+3] # partition the array in groups of 3 elements print a, b, c 

This works because (as stated in the question) there are exactly three parts for each property.

+2
source

If you know that for each there are exactly three parts, but simply:

 a = [3,5,8,3,9,5,0,3,2,7,5,4] print zip(*[iter(a)] * 3) 

Conclusion:

 [(3, 5, 8), (3, 9, 5), (0, 3, 2), (7, 5, 4)] 

This is from this answer.

+2
source
 x = a[::3] y = a[1::3] z = a[2::3] grouped = zip(x,y,z) for p1,p2,p3 in grouped: print p1 + p2 + p3 
+1
source

All Articles