Python:在lis中查找元素

2024-03-29 08:33:46 发布

您现在位置:Python中文网/ 问答频道 /正文

用Python查找列表中元素的索引的好方法是什么?
请注意,列表可能无法排序。

是否有方法指定要使用的比较运算符?


Tags: 方法元素列表排序运算符
3条回答

最好的方法可能是使用list method .index

对于列表中的对象,可以执行以下操作:

def __eq__(self, other):
    return self.Value == other.Value

任何你需要的特殊处理。

您还可以将for/in语句与enumerate(arr)一起使用

查找值为100的项的索引的示例。

for index, item in enumerate(arr):
    if item > 100:
        return index, item

Source

来自Dive Into Python

>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> li.index("example")
5

如果只想知道列表中是否包含元素:

>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> 'example' in li
True
>>> 'damn' in li
False

相关问题 更多 >