我有代码看起来像这样:
thing_index = thing_list.index(thing)
otherfunction(thing_list, thing_index)
确定,所以这是简化,但你得到的想法。现在事情可能不是在列表中,在这种情况下,我想传递-1作为thing_index。在其他语言中,这是你期望index()返回如果它找不到元素。实际上它抛出一个ValueError。
我可以这样做:
try:
thing_index = thing_list.index(thing)
except ValueError:
thing_index = -1
otherfunction(thing_list, thing_index)
但这感觉很脏,加上我不知道ValueError是否可以提出一些其他原因。我想出了基于生成器函数的以下解决方案,但它似乎有点复杂:
thing_index = ( [(i for i in xrange(len(thing_list)) if thing_list[i]==thing)] or [-1] )[0]
有一个更清洁的方式来实现同样的事情吗?让我们假设列表没有排序。