从列表中删除位置 1,2,4,8,16,.. 的项目
Remove items at positions 1,2,4,8,16,.. from list
我将如何删除列表中索引为 2^x 的每个元素?
我试过使用一个 for 循环和一个代表 x 在每个循环中增加 1 的变量,但这会引发超出范围的错误。
例如:
remove([0,0,1,1,0,1,0,1,1])
>>>[1,0,1,0,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]
我会这样做:
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]
。
使用众所周知的 "check if x
is a power of 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}
分析方法:
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]
我将如何删除列表中索引为 2^x 的每个元素? 我试过使用一个 for 循环和一个代表 x 在每个循环中增加 1 的变量,但这会引发超出范围的错误。
例如:
remove([0,0,1,1,0,1,0,1,1])
>>>[1,0,1,0,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]
我会这样做:
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]
。
使用众所周知的 "check if x
is a power of 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}
分析方法:
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]