假设我有一个可以有一个或两个元素的列表:
mylist=["important", "comment"]
或者
mylist=["important"]
然后我希望有一个变量作为标志,这取决于第二个值是否存在。
检查第二个元素是否存在的最佳方法是什么?
我已经用len(mylist)
做过了。如果是2,就可以了。它可以工作,但我更想知道第二个字段是否是“comment”。
然后我找到了这个解决方案:
>>> try:
... c=a.index("comment")
... except ValueError:
... print "no such value"
...
>>> if c:
... print "yeah"
...
yeah
但看起来太长了。你认为可以改进吗?我确信它能但不能设法从Python Data Structures Documentation中找到正确的方法。
使用
in
运算符:啊!错过了你说的那部分,你只想让
"comment"
成为第二个元素。为此,您可以使用:怎么办:
例如:
您可以使用
in
运算符:或者,如果位置很重要,请使用切片:
后者适用于大小为1、2或更大的列表,并且仅当列表的长度为2并且第二个元素等于
'comment'
时才是True
:相关问题 更多 >
编程相关推荐