【问题标题】:Check if a key exists in a Python list检查 Python 列表中是否存在键
【发布时间】:2013-08-07 16:49:09
【问题描述】:

假设我有一个可以包含一个或两个元素的列表:

mylist=["important", "comment"]

mylist=["important"]

然后我希望有一个变量作为标志,这取决于这个第二个值是否存在。

检查第二个元素是否存在的最佳方法是什么?

我已经使用len(mylist) 做到了。如果是2,那就没问题了。它有效,但我想知道第二个字段是否完全是“评论”。

然后我想到了这个解决方案:

>>> try:
...      c=a.index("comment")
... except ValueError:
...      print "no such value"
... 
>>> if c:
...   print "yeah"
... 
yeah

但是看起来太长了。你觉得可以改进吗?我确信它可以但无法从Python Data Structures Documentation 中找到正确的方法。

【问题讨论】:

    标签: python list python-2.7


    【解决方案1】:

    您可以使用in 运算符:

    'comment' in mylist
    

    或者,如果位置很重要,使用切片:

    mylist[1:] == ['comment']
    

    后者适用于大小为 1、2 或更长的列表,并且仅当列表长度为 2 并且第二个元素等于 'comment' 时为 True

    >>> test = lambda L: L[1:] == ['comment']
    >>> test(['important'])
    False
    >>> test(['important', 'comment'])
    True
    >>> test(['important', 'comment', 'bar'])
    False
    

    【讨论】:

      【解决方案2】:

      怎么样:

      len(mylist) == 2 and mylist[1] == "comment"
      

      例如:

      >>> mylist = ["important", "comment"]
      >>> c = len(mylist) == 2 and mylist[1] == "comment"
      >>> c
      True
      >>>
      >>> mylist = ["important"]
      >>> c = len(mylist) == 2 and mylist[1] == "comment"
      >>> c
      False
      

      【讨论】:

        【解决方案3】:

        使用in 运算符:

        >>> mylist=["important", "comment"]
        >>> "comment" in mylist
        True
        

        啊!错过了你所说的部分,你只想"comment" 成为第二个元素。为此,您可以使用:

        len(mylist) == 2 and mylist[1] == "comment"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-02-23
          • 2021-11-15
          • 2021-07-23
          • 2017-02-16
          • 2011-03-19
          • 1970-01-01
          相关资源
          最近更新 更多