如果该项不存在,Python的list.index(x)
会抛出异常。有没有更好的方法来做到这一点,不需要处理异常?
如果你不关心匹配元素的位置,那么使用:
found = x in somelist
如果你关心,那么使用带有LBYL的conditional expression风格:
i = somelist.index(x) if x in somelist else None
为列表实现自己的索引?
class mylist(list):
def index_withoutexception(self,i):
try:
return self.index(i)
except:
return -1
因此,您可以使用list,并使用index2,在出现错误时返回所需内容。
你可以像这样使用它:
l = mylist([1,2,3,4,5]) # This is the only difference with a real list
l.append(4) # l is a list.
l.index_withoutexception(19) # return -1 or what you want
编写一个能够满足您需求的功能:
def find_in_iterable(x, iterable):
for i, item in enumerate(iterable):
if item == x:
return i
return None
如果您只需要知道该项是否存在,而不是索引,则可以使用in
:
x in yourlist
就在这里。你可以,例如。做类似的事情:
test = lambda l, e: l.index(e) if e in l else None
这是这样的:
>>> a = ['a', 'b', 'c', 'g', 'c']
>>> test(a, 'b')
1
>>> test(a, 'c')
2
>>> test(a, 't')
None
所以,基本上,test()
将返回给定列表(第一个参数)中元素的索引(第二个参数),除非它没有被找到(在这种情况下它将返回None
,但它可以是你认为合适的任何东西)。
TL; DR:例外是你的朋友,也是所述问题的最佳方法。
OP在评论中澄清说,对于他们的用例,知道索引是什么并不重要。正如接受的答案所指出的,如果你不在乎,使用x in somelist
是最好的答案。
但我会假设,正如最初的问题所暗示的那样,你确实关心索引是什么。在这种情况下,我会注意到所有其他解决方案都需要扫描列表两次,这会带来很大的性能损失。
此外,正如古老的雷蒙德·黑廷格(Raymond Hettinger)在评论中所写的那样
即使我们有list.find返回-1,你仍然需要测试以查看i == -1并采取一些行动。
因此,我将在原始问题中推迟假设应避免例外。我建议例外是你的朋友。他们没什么可害怕的,他们效率不高,事实上你需要熟悉他们才能编写好的代码。
所以我认为最好的答案是简单地使用try-except方法:
try:
i = somelist.index(x)
except ValueError:
# deal with it
“处理它”只是意味着做你需要做的事情:将i设置为sentinel值,引发你自己的异常,遵循不同的代码分支等。
如果您不关心序列中的位置,只关注它的存在,那么请使用in
运算符。否则,编写一个重构异常处理的函数。
def inlist(needle, haystack):
try:
return haystack.index(needle)
except ...:
return -1
希望这可以帮助
lst= ','.join('qwerty').split(',') # create list
i='a' #srch string
lst.index(i) if i in lst else None
我喜欢使用Web2py's List类,在其胶子包的存储模块中找到。存储模块提供类似列表(List)和类似字典(存储)的数据结构,在未找到元素时不会引发错误。
首先下载web2py's source,然后将gluon包文件夹复制粘贴到python安装的site-packages中。
现在尝试一下:
>>> from gluon.storage import List
>>> L = List(['a','b','c'])
>>> print L(2)
c
>>> print L(3) #No IndexError!
None
注意,它也可以像常规列表一样:
>>> print L[3]
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
l[3]
IndexError: list index out of range
没有内置的方法可以做你想做的事。
这是一个可以帮助你的好帖子:Why list doesn't have safe "get" method like dictionary?