如果列表中不存在该项,Python 的 list.index(x)
会抛出异常。是否有更好的方法可以避免使用异常处理?
如果列表中不存在该项,Python 的 list.index(x)
会抛出异常。是否有更好的方法可以避免使用异常处理?
index()
要慢得多,不是吗?毕竟你必须查找两次:一次是为了存在性,一次是为了索引。这就是为什么C++容器没有exists()
,只有find()
的原因。 - fransi = next((i for i, t in enumerate(somelist) if x == t), None)
。 - AXO如何为列表实现自己的索引?
class mylist(list):
def index_withoutexception(self,i):
try:
return self.index(i)
except:
return -1
所以,您可以使用列表,并使用您的索引2,在出现错误的情况下返回您想要的内容。
您可以像这样使用它:
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
type(l) == list
在这里是 False
。 - bfontainetry:
i = somelist.index(x)
except ValueError:
# deal with it
def find_in_iterable(x, iterable):
for i, item in enumerate(iterable):
if item == x:
return i
return None
如果你只需要知道这个项目是否存在,而不关心索引位置,你可以使用 in
:
x in yourlist
'abc'.find('x') == -1
,但None
也可以。我会更新我的答案。 - Mark Byers是的,可以。您可以类似于以下方式进行操作:
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
,但可以是任何你认为合适的内容)。
in
运算符。否则,编写一个函数来重构异常处理。def inlist(needle, haystack):
try:
return haystack.index(needle)
except ...:
return -1
in
检查存在性并最终返回索引的答案,但是我看到您知道该方法并决定使用可能会抛出的异常处理。我的问题是:为什么您选择捕获异常而不是首先检查haystack
中是否存在needle
?有什么原因吗? - Tadeckexcept ...:
行中,你实际上不需要 ...
。 - swdev>>> 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
def __call__(self, idx, df=None): return self[idx] if 0<=idx<len(self) else df
好主意,谢谢。 - Winand没有内置的方法可以做到你想要做的事情。
这里有一篇很好的帖子,可能会对你有所帮助:为什么列表没有像字典那样安全的“获取”方法?
IndexError: list index out of range
问题,而不是这里描述的 index()
方法和 ValueError: <value> is not in list
问题。 - nealmcblst= ','.join('qwerty').split(',') # create list
i='a' #srch string
lst.index(i) if i in lst else None
None
继续运行。如果缺少索引抛出异常是很有用的,但如果[][0]
抛出异常,我也希望[].index(0)
返回None
,或者至少允许使用[].index(0, default=None)
。这只需要1行代码而不是4行。 - NeilG