从列表中删除位置1,2,4,8,16,...的项目

时间:2015-02-02 23:10:29

标签: python list python-3.x indexing

如何在列表中删除索引为2 ^ x的每个元素? 我尝试使用一个for循环,其中一个变量代表x在每个循环中增加1但是这会抛出超出范围的错误。

e.g:

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

4 个答案:

答案 0 :(得分:3)

如果x是2"位操作技巧 - (x & (x - 1)) == 0

因为在这里你实际上想要检查x + 1,并且在Python == 0中可以包含在隐式真实性检查中......:

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

非常难以理解,唉...! - )

好吧,至少它很容易检查它是否有效......:= _

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

答案 1 :(得分:1)

可能不是最有效的解决方案,但这很简单:

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]

答案 2 :(得分:0)

我就是这样做的:

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()]

这会产生[1, 0, 1, 0, 1]

答案 3 :(得分:0)

分析方法:

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]