Home > Mobile >  Iterative slicing
Iterative slicing

Time:01-22

I am a beginner in programming, I try to learn Python, and I cannot set a correct iterative slincing of my data. I have this:

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 
     12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]

And I would like to obtain this, i.e I do chunks of 3 items and remove half of them:

a = [0, 1, 2,
     6, 7, 8,
     12, 13, 14, 
     18, 19, 20]

I tried a for loop with a % condition, but I cannot set the rule to get what I want ...I did not do maths during years so it's probably a very stupid logical error ...

a = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18, 19, 20, 21, 22, 23]

for i in range (len(a)):
    if i==0 : 
        a=a
    elif (i-3)%6 == 0 :
        a[i:i 4]=[]     
    else :
        a=a
        
print(a)

Thanks a lot in advance for your help !

CodePudding user response:

You could use list comprehension:

result = [val for i in range(0, len(a), 6) for val in a[i:i 3]]

CodePudding user response:

you want this ?

a= [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18, 19, 20, 21, 22, 23]
b = []

for i in range(0,len(a),6):
    for j in range(i,i 3):
        b.append(a[j])

print(b)

CodePudding user response:

I would suggest:

  1. Define new array ( or list )
  2. Defining a counter variable and a keepItem boolean
  3. Loop through the array and add 1 to the counter at every step
  4. If the counter is 3 then set it to 0 and flip the boolean value
  5. If your keepItem boolean is true then add that item to the new array

I would suggest defining edgecases. For example, what happens when the length of the array is not a multiple of 3?

This should be a good starting point!

Goodluck!

CodePudding user response:

With a list comprehension and integer operations:

[v for v in a if (v // 3) % 2 == 0]

This of course assumes that you're working on a sorted list with values from 0-n, as in the example. If you still want to use this method, you can use enumerate, too:

[v for i, v in enumerate(a) if (i // 3) % 2 == 0]
  •  Tags:  
  • Related