Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating Through List by 3's

Tags:

python

list

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

This gets me the first and every 3 item. 3,3,0,7

is there a way i can retrieve the next two items as well?

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 that's not correct 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 retrieve all three parts of the property from the list.

like image 303
Coo Jinx Avatar asked Jun 11 '12 21:06

Coo Jinx


People also ask

How to iterate over a list in Python?

There are multiple ways to iterate over a list in Python. Let’s see all the different ways to iterate over a list in Python, and performance comparison between them. Method #1: Using For loop. Python3. list = [1, 3, 5, 7, 9] for i in list: print(i) Output: 1 3 5 7 9.

How do you iterate through a list in Java?

Iterate through List in Java. 1 Using loops (Naive Approach) For loop For-each loop While loop. 2 Using Iterator. 3 Using List iterator. 4 Using lambda expression. 5 Using stream.forEach () Method 1-A: Simple for loop.

How do you iterate over a list in C with Loop?

Method 1-C: Using a while loop. Iterating over a list can also be achieved using a while loop. The block of code inside the loop executes until the condition is true. A loop variable can be used as an index to access each element.

How to group the elements of list and iterate through them?

Grouper is function which we can use to group the elements of list and iterate through them. This can be useful if you want to iterate 2-3 items per batch of your iterable. Required. A sequence of a list, collection, or an iterator object. Required. The number of elements to group per batch.


2 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)]
like image 154
Sven Marnach Avatar answered Nov 09 '22 20:11

Sven Marnach


Try this:

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

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

like image 28
Óscar López Avatar answered Nov 09 '22 22:11

Óscar López