简体   繁体   中英

Remove items at positions 1,2,4,8,16,.. from list

How would I go about removing every element with index 2^x in a list? I've tried using a for loop with a variable representing x increasing by 1 in every loop but this throws the out of range error.

eg:

remove([0,0,1,1,0,1,0,1,1])
>>>[1,0,1,0,1]

It's an irresistible temptation here to use the well-known "check if x is a power of 2" bit-manipulation trick -- (x & (x - 1)) == 0 .

Since here you actually want to check x + 1 , and in Python == 0 can be subsumed in an implicit truthiness check...:

def remove(listarg):
    return [it for x, it in enumerate(listarg) if (x & (x+1))]

Pretty inscrutable, alas...!-)

Ah well, at least it's easy to check it works...:=_

>>> set(range(1,35)).difference(remove(range(1,35)))
{32, 1, 2, 4, 8, 16}

Probably not the most efficient solution, but this is nice and simple:

import math

orig = [0,0,1,1,0,1,0,1,1]

max_power_of_2 = int(math.log(len(orig), 2))
# Only generate these up to the length of the list
powers_of_2 = set(2**n for n in range(max_power_of_2 + 1))

# Your example output implies you're using 1-based indexing,
#   which is why I'm adding 1 to the index here
cleaned = [item for index, item in enumerate(orig) 
           if not index + 1 in powers_of_2]

In [13]: cleaned
Out[13]: [1, 0, 1, 0, 1]

This is how I'd do it:

from math import log

my_list  = [0,0,1,1,0,1,0,1,1]
new_list = [item for i,item in enumerate(my_list,1) if not log(i,2).is_integer()]

This yields [1, 0, 1, 0, 1] .

Analytical approach:

from math import ceil, log

def remove(list_):
    """ Create new list with every element with index 2**x removed. """
    indices = set((2**i-1 for i in range(int(ceil(log(len(list_), 2)))+1)))
    return [elem for i, elem in enumerate(list_) if i not in indices]

print(remove([0,0,1,1,0,1,0,1,1]))  # --> [1, 0, 1, 0, 1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM