[英]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.