[英]IndexError in Python (Beginner)
我有一个数组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
如果我删除两个delete语句之一,它不会给我一个错误,它将从[...,1,0,...]
删除1
[...,1,0,...]
但保留0
。
例如。
X[1] = [5, 4, 4, 5, 7, 1, 0, 3, 2, 1]
删除1条delete语句后,输出为
[5, 4, 4, 5, 7, 10, 0, 3, 2, 1]
但是用2条delete语句,我得到一个错误。
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
在循环的第一次迭代中, 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
开头,则我的原始答案不变。 假设它从未按照OP的建议进行操作,那么让我们看看为什么两个删除会导致问题。
X[1] = [5, 4, 4, 5, 7, 1, 0, 3, 2, 1]
for循环计算for m in range(0, 10)
。 当我们到达0
, m == 6
。 因此,我们在位置5
*之前插入10
,并两次删除位置6
。
X[1] = [5, 4, 4, 5, 7, 10, 3, 2, 1]
注意那里只有9个元素吗? for
循环中的len(X[1])
永远不会重新评估 ,因此它将在数组末尾运行,从而产生超出范围的错误。
测试程序:
>>> 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
的定义:
list.insert(i,x)
在给定位置插入项目。 第一个参数是要插入元素的索引,因此a.insert(0,x)插入列表的最前面,而a.insert(len(a),x)等效于a.append( X)。
这是一个简单的方法。
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=[...]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.