在python中处理list.index(可能不存在)的最佳方法是什么? [英] Best way to handle list.index(might-not-exist) in python?

查看:328
本文介绍了在python中处理list.index(可能不存在)的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  thing_index = thing_list.index(thing)
otherfunction( thing_list,thing_index)

好吧,这是简化的,但你明白了。现在 thing 可能实际上不在列表中,在这种情况下,我想以 thing_index 的形式传递-1。在其他语言中,如果找不到元素,则返回 index()。事实上,它会抛出 ValueError

我可以这样做:

  try:
thing_index = thing_list.index(thing)
除了ValueError:
thing_index = -1
otherfunction(thing_list ,thing_index)

但是这感觉很脏,再加上我不知道 ValueError 可能因其他原因而被引发。我想出了以下基于生成器函数的解决方案,但它似乎有点复杂:

  thing_index =([(i for我在xrange(len(thing_list))如果thing_list [i] == thing)]或[-1])[0] 

是否有一个更清晰的方法来实现相同的事情?假设列表没有排序。

解决方案

使用try-except子句没有什么脏这是pythonic的方式。 ValueError 将仅由 .index 方法引发,因为它是您在那里唯一的代码!



回答评论:

在Python中, 更容易要求原谅而不是获得许可 理念已经确立, no index 不会引发任何其他问题的这种类型的错误。不是我能想到的。

I have code which looks something like this:

thing_index = thing_list.index(thing)
otherfunction(thing_list, thing_index)

ok so that's simplified but you get the idea. Now thing might not actually be in the list, in which case I want to pass -1 as thing_index. In other languages this is what you'd expect index() to return if it couldn't find the element. In fact it throws a ValueError.

I could do this:

try:
    thing_index = thing_list.index(thing)
except ValueError:
    thing_index = -1
otherfunction(thing_list, thing_index)

But this feels dirty, plus I don't know if ValueError could be raised for some other reason. I came up with the following solution based on generator functions, but it seems a little complex:

thing_index = ( [(i for i in xrange(len(thing_list)) if thing_list[i]==thing)] or [-1] )[0]

Is there a cleaner way to achieve the same thing? Let's assume the list isn't sorted.

解决方案

There is nothing "dirty" about using try-except clause. This is the pythonic way. ValueError will be raised by the .index method only, because it's the only code you have there!

To answer the comment:
In Python, easier to ask forgiveness than to get permission philosophy is well established, and no index will not raise this type of error for any other issues. Not that I can think of any.

这篇关于在python中处理list.index(可能不存在)的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆