如何忽略添加到Python列表中的特定元素

我有一个python列表。假设它是一个空列表。有什么方法可以使列表忽略在列表创建本身时有人尝试添加的特定字符。

假设我想忽略所有的“。” 当有人尝试使用 list.append('.') 附加字符时要忽略的字符。

有没有办法在创建列表时提到这一点?


ITMISS
浏览 176回答 3
3回答

幕布斯6054654

您可以创建一个特殊的附加函数,如果字符不是 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']

慕尼黑的夜晚无繁华

在python中执行此操作的最佳方法是创建具有所需行为的新类>>> class mylist(list):...     def append(self, x):...             if x != ".":...                     super().append(x)... >>> l = mylist()>>> l.append("foo")>>> l['foo']>>> l.append(".")>>> l['foo']

猛跑小猪

我认为您不应该这样做,但是如果确实需要,可以将列表子类化,如下所示: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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python