给定一个零和边界元素(1)的列表是否有一种有效的方法来替换零,如果它们之间少于N个呢?
For N=3:
[1,0,0,1,1,1,0,0,0,1,0,0,0] => [1,1,1,1,1,1,0,0,0,1,0,0,0]
更多案例:
[1,0,0,1] => [1,1,1,1]
[0,0,1] => [0,0,1]
[1,0,0] => [1,0,0]
答案 0 :(得分:2)
您可以使用1
的索引,并检查它们是否是n
个元素。这应该有效:
l = [1,0,0,1,1,1,0,0,0,1,0,0,0]
n = 3
indexList = [i for i,j in enumerate(l) if j ==1]
for i in range(len(indexList)):
try:
if indexList[i+1] - indexList[i] < n+1:
tmp = [1 for j in range(indexList[i+1] - indexList[i])]
l[indexList[i]:indexList[i+1]] = tmp
except IndexError:
pass
输出:
>>> l
[1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0]
答案 1 :(得分:1)
您可以将list
转换为str
并使用replace
方法,然后转换回list
:
data = [1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0]
n = 3
repl = (("1" + "0" * i + "1", "1" + "1" * i + "1") for i in range(1, n))
data_str = "".join(str(i) for i in data)
for r in repl:
while True:
new_str = data_str.replace(r[0], r[1])
if new_str == data_str:
break
else:
data_str = new_str
new_data = list(int(s) for s in data_str)
print(new_data)
这将打印
[1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0]
它看起来有点复杂,但如果你有小型列表不会导致任何内存问题,那么工作正常。
答案 2 :(得分:1)
您可以使用list
的堆叠功能。运行数字列表并将其添加到堆栈,计算添加的零的数量,并在跟随1时将其与N
进行比较,然后在count
&lt; count
:
N
追加为data = [1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0]
n = 3
new_data = []
zeros_found = 0
for number in data:
if number == 0:
zeros_found += 1
elif 0 < zeros_found < n:
for i in range(0, zeros_found):
new_data.pop()
zeros_found = 0
new_data.append(number)
data = new_data
,并且从堆栈弹出O(1)
,因此复杂性为O(1)
,您将使用额外的空间
与同事讨论后得到这个解决方案
答案 3 :(得分:1)
您可以对原始数据进行行程编码并根据该表示进行更改:
In [12]: import itertools
In [13]: data = [1,0,0,1,1,1,0,0,0,1,0,0,0]
In [14]: N = 3
In [15]: def run_length_encode(it):
...: for k, g in itertools.groupby(it):
...: yield k, sum(1 for _ in g)
...:
In [16]: s = itertools.chain.from_iterable([1 if n < N else k]*n for k, n in run_length_encode(data))
In [17]: list(s)
Out[17]: [1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0]