检查Python lis中是否存在密钥

2024-06-14 21:08:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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

mylist=["important", "comment"]

或者

mylist=["important"]

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

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

我已经用len(mylist)做过了。如果是2,就可以了。它可以工作,但我更想知道第二个字段是否是“comment”。

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

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

但看起来太长了。你认为可以改进吗?我确信它能但不能设法从Python Data Structures Documentation中找到正确的方法。


Tags: 方法元素列表indexlen标志comment解决方案
3条回答

使用in运算符:

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

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

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

怎么办:

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

您可以使用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

相关问题 更多 >