检查 Python 列表中是否存在键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18084263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:53:24  来源:igfitidea点击:

Check if a key exists in a Python list

pythonlistpython-2.7

提问by fedorqui 'SO stop harming'

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). If it is 2, it is fine. It works but I would prefer to know if the 2nd field is exactly "comment" or not.

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

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

采纳答案by arshajii

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

回答by Rohit Jain

Use inoperator:

使用in运算符:

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

Ah! Missed the part where you said, you just want "comment"to be the 2nd element. For that you can use:

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

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

回答by Martijn Pieters

You can use the inoperator:

您可以使用in运算符:

'comment' in mylist

or, if the positionis important, use a slice:

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

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

The latter works for lists that are size one, two or longer, and only is Trueif the list is length 2 andthe second element is equal to 'comment':

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

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