Search code examples
pythonnested-loops

Nested for-loop the pythonic way to structure data?


I have structured data in some sources and ultimately I would like to step through each source, by the same amount, but starting at different indexes, in order to re-structure the data.

I will go on to perform analysis on each item contained in each iterated slice of source. What is the python way to do this? A nested for loop?

sources = ('source1', 'source2' 'source3')
for source in sources:
    slices = ('[1::5]', '[2::5]''[3::5]')
    for slice in slices:
        iteratedSlice = source[slice] 

Solution

  • A nested for loop with slice is a good starting point:

    sources = [source1, source2, source3]
    slices = [slice(1,None,5), slice(2,None,5), slice(3,None,5)]
    
    for source in sources:
        for s in slices:
            iteratedSlice = source[s]