2024-03-29 08:33:46 发布
网友
用Python查找列表中元素的索引的好方法是什么? 请注意,列表可能无法排序。
是否有方法指定要使用的比较运算符?
最好的方法可能是使用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
最好的方法可能是使用list method .index。
对于列表中的对象,可以执行以下操作:
任何你需要的特殊处理。
您还可以将for/in语句与enumerate(arr)一起使用
查找值为100的项的索引的示例。
Source
来自Dive Into Python:
如果只想知道列表中是否包含元素:
相关问题 更多 >
编程相关推荐