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.
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.
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.
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.
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.
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)]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With