[英]Check if a key exists in a Python list
假设我有一个可以有一个或两个元素的列表:
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数据结构文档中找到正确的方法。
您可以使用in
运算符:
'comment' in mylist
或者,如果位置很重要,请使用切片:
mylist[1:] == ['comment']
后者适用于大小为一,二或更长的列表,如果列表长度为2 且第二个元素等于'comment'
,则仅为True
:
>>> test = lambda L: L[1:] == ['comment']
>>> test(['important'])
False
>>> test(['important', 'comment'])
True
>>> test(['important', 'comment', 'bar'])
False
关于什么:
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
运营商中使用:
>>> mylist=["important", "comment"]
>>> "comment" in mylist
True
啊! 错过了你所说的部分,你只想让"comment"
成为第二个元素。 为此您可以使用:
len(mylist) == 2 and mylist[1] == "comment"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.