[英]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]
使用眾所周知的“檢查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))]
挺不可思議的,a ...!-)
嗯,至少可以很容易地檢查它是否有效...:= _
>>> set(range(1,35)).difference(remove(range(1,35)))
{32, 1, 2, 4, 8, 16}
可能不是最有效的解決方案,但這很簡單:
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]
1,0,1,0,1 [1, 0, 1, 0, 1]
。
分析方法:
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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.