Python:调整项目附加到列表

时间:2012-12-01 13:16:09

标签: python list append

我是Python的初学者,我有一个简短的问题,我无法找到解决方案:

有没有办法规范列表中被覆盖的内容?例如,我有一个填充零的列表,然后我将逐渐填充其他元素,我希望能够做的是在覆盖零以外的其他内容时创建错误。有没有聪明的方法来做到这一点?

我可以使用类似的东西:

a = [0, 1, 0, 1, 0, 0, 0, 0]
b = []
[i for i, e in enumerate(a) if e != 0]
return False 

或类似的东西?

1 个答案:

答案 0 :(得分:2)

您可以使用函数更改列表中的元素,以检查元素是否为0

def setElement(l, index, element):
    '''Change the element from given list(l) at given index.'''
    if l[index] != 0:
        raise Exception("Attempt to overwrite %s instead of 0" %l[index])
    else:
        l[index] = element

现在您可以通过调用setElement(<list>, <index>, <element>)

来使用它
 In[1]: a = [0, 0, 0, 0, 0, 0, 0]

 In[2]: setElement(a, 2, 3)

 In[3]: setElement(a, len(a)-1, "Last Element!")

 In[4]: setElement(a, len(a)-1, 53)
Out[4]: Attempt to overwrite "Last Element!" instead of 0

 In[5]: print(a)
Out[5]: [0, 0, 3, 0, 0, 0, "Last Element"]