Home > OS >  skipping a certain range of a list at time in python
skipping a certain range of a list at time in python

Time:06-04

I have a array, I want to pick first 2 or range, skip the next 2, pick the next 2 and continue this until the end of the list

list = [2, 4, 6, 7, 9,10, 13, 11, 12,2]
results_wanted = [2,4,9,10,12,2] # note how it skipping 2. 2 is used here as and example

Is there way to achieve this in python?

CodePudding user response:

from itertools import compress, cycle

results = list(compress(lst, cycle([1,1,0,0])))

or

results = [x for i, x in enumerate(lst) if i % 4 < 2]

or one that should be fast:

a = lst[::4]
b = lst[1::4]
results = [None] * (len(a)   len(b))
results[::2] = a
results[1::2] = b

Or if it's ok to modify the given list instead of building a new one:

del lst[2::4], lst[2::3]

CodePudding user response:

Taking n number of elements and skipping the next n.

l = [2, 4, 6, 7, 9, 10, 13, 11, 12, 2]
n = 2
wanted = [x for i in range(0, len(l), n   n) for x in l[i: i   n]]
### Output : [2, 4, 9, 10, 12, 2]

CodePudding user response:

I didn't use any python prebuild techniques. I used traditional for loop with if-else conditions

  1. We have to skip based on a particular number.
  2. This skip needs to be done based on boolean parameter which I defined as skipMode
  3. if skipMode is true then the digits will not be added to the list 4 this skipMode will be changed based on the skipNumber
test = [2, 4, 6, 7, 9,10, 13, 11, 12,2]

def skipElementsByPositions(test,skip):
    if(skip> len(test)):
        return -1
    else:
        desireList = []
        skipMode = False
        for i in range(0,len(test)):
            if skipMode==False:
                desireList.append(test[i])
            if (i 1)%skip==0:
                skipMode=not skipMode
        return desireList

print(skipElementsByPositions(test,2)) #2,4,9,10,12,2
print(skipElementsByPositions(test,3)) #2, 4, 6, 13, 11, 12

CodePudding user response:

You can try to iterate using range(start, end, skip)

And you can specify how many to add (add=2) and how many to skip (skip=2) in the sequence

list1 = [2, 4, 6, 7, 9,10, 13, 11, 12,2, 4, 6, 7, 9,10, 13, 11, 12,2]
list2 = []
add = 2
skip = 2

for i in range(0, len(list1), skip add):
    list2  = list1[i:i add]

print(list2)

Output:

[2, 4, 9, 10, 12, 2, 7, 9, 11, 12]

By the way you should avoid using the Python reserved word list as a variable name.

CodePudding user response:

As you have a tag, here are numpy approaches.

Using a mask:

lst = [2, 4, 6, 7, 9,10, 13, 11, 12,2]
a = np.array(lst)

mask = [True, True, False, False]
n = (len(a) 3)//4
a[np.tile(mask, n)[:len(a)]]

Or with intermediate reshaping into a 2D array:

n = (len(a) 3)//4
extra = n*4-len(a)
(np
  .pad(a, (0, extra), mode='constant', constant_values=0)
  .reshape(-1,4)
  [:,:2]
  .ravel()
  )

Output: array([ 2, 4, 9, 10, 12, 2])

  • Related