我有一个数组X [1]。在那个数组中,我想用[....,10,..]替换元素[...,1,0,...]。换句话说,无论1和0连续出现在哪里,我都想用10替换它。
我的代码是,
for m in range(0,len(X[1])):
if X[1][m] == 0:
X[1].insert(m-1,10)
del X[1][m]
del X[1][m]
但是这段代码给了我错误:
Traceback (most recent call last):
File "gettinginput.py", line 25, in <module>
if X[1][m] == 0:
IndexError: list index out of range
如果我删除了两个删除语句中的一个,它不会给我一个错误,它会从1
删除[...,1,0,...]
,但会离开0
。
例如
X[1] = [5, 4, 4, 5, 7, 1, 0, 3, 2, 1]
删除1个删除语句后,输出为
[5, 4, 4, 5, 7, 10, 0, 3, 2, 1]
但是有2个删除语句,我收到错误。
答案 0 :(得分:2)
def reduce_list(lst, match, replace):
_matchlen = len(match)
lst = list(lst) # copy existing list
for i in xrange(len(lst)-_matchlen, -1, -1): # scan through it backwards
if lst[i:i+_matchlen] == match:
lst[i:i+_matchlen] = replace
return lst
print reduce_list([1,0,1,0,1,1,0], [1,0], [10])
结果
[10, 10, 1, 10]
为了符合你的例子,
X[1] = reduce_array(X[1], [1,0], [10])
编辑后再考虑一下,
def reduce_list(lst, match, replace):
"""
Return a new list,
with all original non-overlapping occurrences of 'match'
replaced by 'replace'
"""
lst = list(lst) # copy existing list
matchlen = len(match)
replacelen = len(replace)
last_i = len(lst) - matchlen
i = 0
while i <= last_i:
if lst[i:i+matchlen] == match:
lst[i:i+matchlen] = replace
last_i += replacelen - matchlen
i += replacelen
else:
i += 1
return lst
答案 1 :(得分:1)
在循环的第一次迭代中,m == 0
。然后你插入m-1
-1
,这将是X[1]
,这肯定超出了for m in range(0,len(X[1])):
if X[1][m] == 0:
X[1].insert(m-1,10)
del X[1][m]
del X[1][m]
的范围。
0
编辑:如果输入以X[1] = [5, 4, 4, 5, 7, 1, 0, 3, 2, 1]
开头,我原来的答案就是。假设它从未像OP建议那样做,那么让我们看看为什么这两个删除会导致问题。
for m in range(0, 10)
for循环评估为0
。当我们到达m == 6
,10
时。因此,我们在位置5
*之前插入6
,并删除位置X[1] = [5, 4, 4, 5, 7, 10, 3, 2, 1]
两次。
len(X[1])
请注意,那里只有9个元素? for
循环中的>>> for m in range(len(x)):
... del(x[m])
... print(len(x))
...
8
7
6
5
4
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
IndexError: list assignment index out of range
永远不会重新评估,因此它会在数组末尾运行,从而导致超出范围错误。
测试程序:
insert
<小时/> *为什么在位置5之前?根据{{1}}:
的定义
list.insert(i,x)
在指定位置插入项目。第一个参数是要插入的元素的索引,因此a.insert(0,x)插入列表的前面,而a.insert(len(a),x)等同于a.append( x)的
答案 2 :(得分:1)
这是一个简单的方法。
lst=[5, 4, 4, 5, 7, 1, 0, 3, 2, 1]
for idx,val in enumerate(lst[:-1]):
if(val==1 and lst[idx+1]==0):
lst[idx:idx+1]=[10]
print (lst)
或没有enumerate
:
for idx in range(len(lst)-1):
if(lst[idx:idx+1]==[1,0]):
lst[idx:idx+1]=[10]
print (lst)
我们在列表中搜索寻找子列表[1,0],然后用(子)列表[10]替换该子列表。
当然,在完成所有这些操作之前,如果您有一个列表(X
),则可以lst=X[1]
代替lst=[...]