函数,该函数在找不到任何东西时不会抛出异常

如果该项不存在,Python 的 list.index(x)将引发异常。有没有不需要处理异常的更好方法?

69505 次浏览

写一个函数来完成你需要的任务:

def find_in_iterable(x, iterable):
for i, item in enumerate(iterable):
if item == x:
return i
return None

如果只需要知道该项是否存在,而不需要知道索引,则可以使用 in:

x in yourlist

如果您不关心它在序列中的位置,只关心它的存在,那么使用 in操作符。否则,编写一个重构异常处理的函数。

def inlist(needle, haystack):
try:
return haystack.index(needle)
except ...:
return -1

实现自己的列表索引?

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

There is no built-in way to do what you want to do.

这里有一个很好的职位,可能会帮助你: 为什么 list 没有像 dictionary 那样的安全“ get”方法?

是的,有。你可以做类似的事情:

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,但它可以是任何您认为合适的)。

如果您不关心匹配元素在哪里,那么使用:

found = x in somelist

如果你真的关心,那么使用 LBYL风格和 条件表达式:

i = somelist.index(x) if x in somelist else None

希望这能帮上忙

lst= ','.join('qwerty').split(',') # create list
i='a'  #srch string
lst.index(i) if i in lst else None

I like to use Web2py 的 名单 class, found in the storage module of its gluon package. The storage module offers list-like (List) and dictionary-like (Storage) data structures that do not raise errors when an element is not found.

首先下载 Web2py 的来源,然后将胶子包文件夹复制粘贴到 Python 安装的站点包中。

现在试试看:

>>> 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

例外是你的朋友,也是解决问题的最佳方法。
It's easier to ask for forgiveness than permission (EAFP)

OP 在一条注释中澄清说,对于他们的用例来说,知道索引是什么实际上并不重要。作为公认的答案注意,使用 x in somelist是最好的答案,如果你不在乎。

但是我假设,正如最初的问题所暗示的那样,关心的是指数是什么。在这种情况下,我将注意到所有其他解决方案都需要扫描列表两次,这可能会带来很大的性能损失。

此外,正如德高望重的雷蒙德 · 海廷格(Raymond Hettinger)在评论中所写的那样

即使我们有返回 -1的 list.find,您仍然需要测试 i = = -1并采取一些行动。

因此,我将推翻最初问题中的假设,即应该避免异常。我建议例外是你的朋友。它们没有什么好害怕的,它们并不低效,事实上,要编写好的代码,您需要熟悉它们。

因此,我认为最好的解决办法就是简单地使用除了尝试以外的方法:

try:
i = somelist.index(x)
except ValueError:
# deal with it

"接受现实吧" just means do what you need to do: set i to a sentinel value, raise an exception of your own, follow a different code branch, etc.

这个例子说明了为什么 Python 原则 请求原谅比请求许可更容易(EAFP)有意义,与 三思而后行(LBYL)的 if-then-else 风格形成对比