3 回答

TA贡献1876条经验 获得超7个赞
您可以创建一个特殊的附加函数,如果字符不是 a ,则该函数会就地修改列表'.':
def append_no_dot(l, c):
if c != '.': l.append(c)
>>> l = ['a','b']
>>> append_no_dot(l, 'c')
>>> append_no_dot(l, '.')
>>> l
['a', 'b', 'c']

TA贡献1864条经验 获得超6个赞
在python中执行此操作的最佳方法是创建具有所需行为的新类
>>> class mylist(list):
... def append(self, x):
... if x != ".":
... super().append(x)
...
>>> l = mylist()
>>> l.append("foo")
>>> l
['foo']
>>> l.append(".")
>>> l
['foo']

TA贡献1858条经验 获得超8个赞
我认为您不应该这样做,但是如果确实需要,可以将列表子类化,如下所示:
class IgnoreList(list):
def append(self, item, *args, **kwargs):
if item == '.':
return
return super(IgnoreList, self).append(item)
但是非常不符合pythonic。更好的解决方案是只在调用append之前检查该值。
if value != '.':
my_list.append(value)
添加回答
举报