Python检查一个项目是否在列表中
对不起,我非常喜欢python的初学者。我想要做的就是看它列出的项目是什么,我有一些名单设置,如:。Python检查一个项目是否在列表中
l1 = [1,2,3]
l2 = [4,5,6]
l3 = [7,8,9]
而且我们说,我想找到其中列出5项是在 我”什么目前正在做的是:
if l1.index(5)!=False:
print 1
elif l2.index(5)!=False:
print 2
elif l3.index(5)!=False:
print 3
但这不起作用。我将如何做到这一点?
if l1.index(5)!=False: print 1
的index()
方法不返回真或假,它返回索引。所以,你会更改为:
if l1.index(5) >= 0:
print 1
之前不知道该操作员如果它不在列表中,该怎么办? –
这就是[docs](https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range)的用途:)。实际上,它会引发ValueError。从Java切换回来我以为它会返回-1。至少关于不将返回值与布尔文字相比较的部分是正确和有用的。 – dsh
为什么要留下不正确的部分? –
的可能重复[Python的:查找表(http://stackoverflow.com/questions/9542738/python-find-in-list) –