【问题标题】:How to ignore specific elements being added to Python list如何忽略添加到 Python 列表中的特定元素
【发布时间】:2019-01-29 03:45:47
【问题描述】:

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

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

在创建列表时有什么方法可以提及吗?

【问题讨论】:

  • 谁是“某人”,他们为什么要将这些不需要的项目附加到列表中,为什么您希望列表本身负责忽略这些项目?
  • 你试过子类化`list吗?
  • 有人就是我。我有一个限制,即在意外或故意附加时忽略指定字符的列表。

标签: python python-3.x python-2.7 list character


【解决方案1】:
class IgnoreList(list):

    def __init__(self, ignore_me):
        self.ignore_me = ignore_me

    def check(self, v):
        return v == self.ignore_me

    def append(self, v):
        if not self.check(v):
            super(IgnoreList, self).append(v)


my_list = IgnoreList('x')        # `x` to be ignored here
my_list.append('a')
my_list.append('b')
my_list.append('x')
my_list.append('c')
print my_list

######OUTPUT########
['a', 'b', 'c']

【讨论】:

  • 我们能不能用简单的方式做同样的事情。不像你上面提到的那样太复杂和太大@Vishvajit Pathak
  • @SukumarRdjf 这是最好的方法,它涵盖了可能对您有用的其他要求。
【解决方案2】:

如果字符不是'.',您可以创建一个特殊的附加函数来修改列表:

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']

【讨论】:

    【解决方案3】:

    在 python 中执行此操作的最佳方法是创建一个具有所需行为的新类

    >>> class mylist(list):
    ...     def append(self, x):
    ...             if x != ".":
    ...                     super().append(x)
    ... 
    >>> l = mylist()
    >>> l.append("foo")
    >>> l
    ['foo']
    >>> l.append(".")
    >>> l
    ['foo']
    

    【讨论】:

      【解决方案4】:

      我认为你不应该这样做,但如果你真的必须这样做,你可以像这样子类化一个列表:

      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)
      

      【讨论】:

        猜你喜欢
        • 2018-10-16
        • 1970-01-01
        • 2016-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多