0

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

有什么方法可以规范列表中覆盖的内容吗?例如,我有一个用零填充的列表,然后我将逐渐用其他元素填充,我想要做的是在覆盖零以外的东西时创建一个错误。有什么聪明的方法可以做到这一点吗?

我可以使用类似的东西:

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

或类似的东西?

4

1 回答 1

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"]
于 2012-12-01T13:50:13.073 回答