fed*_*qui 18 python list python-2.7
假设我有一个可以有一个或两个元素的列表:
mylist=["important", "comment"]
Run Code Online (Sandbox Code Playgroud)
要么
mylist=["important"]
Run Code Online (Sandbox Code Playgroud)
然后我希望有一个变量作为标志,取决于第二个值是否存在.
检查第二个元素是否存在的最佳方法是什么?
我已经用它了len(mylist).如果是2,那很好.它有效,但我更愿意知道第二个字段是否恰好是"评论".
然后我来到这个解决方案:
>>> try:
... c=a.index("comment")
... except ValueError:
... print "no such value"
...
>>> if c:
... print "yeah"
...
yeah
Run Code Online (Sandbox Code Playgroud)
但看起来太长了.你认为它可以改善吗?我确信它可以但无法从Python数据结构文档中找到正确的方法.
Mar*_*ers 33
您可以使用in运营商:
'comment' in mylist
Run Code Online (Sandbox Code Playgroud)
或者,如果位置很重要,请使用切片:
mylist[1:] == ['comment']
Run Code Online (Sandbox Code Playgroud)
后者适用于大小为一,二或更长True的列表,并且仅当列表长度为2 且第二个元素等于'comment':
>>> test = lambda L: L[1:] == ['comment']
>>> test(['important'])
False
>>> test(['important', 'comment'])
True
>>> test(['important', 'comment', 'bar'])
False
Run Code Online (Sandbox Code Playgroud)
ars*_*jii 13
关于什么:
len(mylist) == 2 and mylist[1] == "comment"
Run Code Online (Sandbox Code Playgroud)
例如:
>>> 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
Run Code Online (Sandbox Code Playgroud)
Roh*_*ain 12
使用in运算符:
>>> mylist=["important", "comment"]
>>> "comment" in mylist
True
Run Code Online (Sandbox Code Playgroud)
啊! 错过了你所说的部分,你只想"comment"成为第二个元素.为此您可以使用:
len(mylist) == 2 and mylist[1] == "comment"
Run Code Online (Sandbox Code Playgroud)