[英]Check if a key exists in a Python list
Suppose I have a list that can have either one or two elements: 假设我有一个可以有一个或两个元素的列表:
mylist=["important", "comment"]
or 要么
mylist=["important"]
Then I want to have a variable to work as a flag depending on this 2nd value existing or not. 然后我希望有一个变量作为标志,取决于第二个值是否存在。
What's the best way to check if the 2nd element exists? 检查第二个元素是否存在的最佳方法是什么?
I already did it using len(mylist)
. 我已经使用
len(mylist)
完成了它。 If it is 2, it is fine. 如果是2,那很好。 It works but I would prefer to know if the 2nd field is exactly "comment" or not.
它有效,但我更愿意知道第二个字段是否恰好是“评论”。
I then came to this solution: 然后我来到这个解决方案:
>>> try:
... c=a.index("comment")
... except ValueError:
... print "no such value"
...
>>> if c:
... print "yeah"
...
yeah
But looks too long. 但看起来太长了。 Do you think it can be improved?
你认为它可以改善吗? I am sure it can but cannot manage to find a proper way from the Python Data Structures Documentation .
我确信它可以但无法从Python数据结构文档中找到正确的方法。
You can use the in
operator: 您可以使用
in
运算符:
'comment' in mylist
or, if the position is important, use a slice: 或者,如果位置很重要,请使用切片:
mylist[1:] == ['comment']
The latter works for lists that are size one, two or longer, and only is True
if the list is length 2 and the second element is equal to 'comment'
: 后者适用于大小为一,二或更长的列表,如果列表长度为2 且第二个元素等于
'comment'
,则仅为True
:
>>> test = lambda L: L[1:] == ['comment']
>>> test(['important'])
False
>>> test(['important', 'comment'])
True
>>> test(['important', 'comment', 'bar'])
False
What about: 关于什么:
len(mylist) == 2 and mylist[1] == "comment"
For example: 例如:
>>> 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
Use in
operator: in
运营商中使用:
>>> mylist=["important", "comment"]
>>> "comment" in mylist
True
Ah! 啊! Missed the part where you said, you just want
"comment"
to be the 2nd element. 错过了你所说的部分,你只想让
"comment"
成为第二个元素。 For that you can use: 为此您可以使用:
len(mylist) == 2 and mylist[1] == "comment"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.