检查Python列表中是否存在密钥

时间:2013-08-06 15:21:54

标签: python list python-2.7

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

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找到正确的方法。

3 个答案:

答案 0 :(得分:31)

您可以使用in运算符:

'comment' in mylist

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

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

后者适用于大小为一,二或更长的列表,如果列表长度为2 ,则第二个元素等于True,则只有'comment'

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

答案 1 :(得分:11)

怎么样:

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

答案 2 :(得分:9)

使用in运算符:

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

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

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