Python:在列表中查找元素 [英] Python: finding an element in a list
本文介绍了Python:在列表中查找元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python中找到列表中元素索引的好方法是什么?
请注意,列表可能未排序.
What is a good way to find the index of an element in a list in Python?
Note that the list may not be sorted.
是否可以指定要使用的比较运算符?
Is there a way to specify what comparison operator to use?
推荐答案
最好的方法可能是使用列表方法.index .
The best way is probably to use the list method .index.
对于列表中的对象,您可以执行以下操作:
For the objects in the list, you can do something like:
def __eq__(self, other):
return self.Value == other.Value
具有您需要的任何特殊处理.
with any special processing you need.
您还可以将for/in语句与enumerate(arr)一起使用
You can also use a for/in statement with enumerate(arr)
查找值大于100的项目的索引的示例.
Example of finding the index of an item that has value > 100.
for index, item in enumerate(arr):
if item > 100:
return index, item
这篇关于Python:在列表中查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文