相关疑难解决方法(0)

如何查找列表中所有出现的元素?

index()只会在列表中首次出现一个项目.是否有一个巧妙的技巧可以返回列表中的所有索引?

python list

326
推荐指数
9
解决办法
35万
查看次数

Python中的EAFP原理是什么?

Python中"使用EAFP原理"是什么意思?你能提供任何例子吗?

python principles

123
推荐指数
3
解决办法
3万
查看次数

列表中的项目的Python索引没有错误?

可能重复:
Python list.index问题

要查找列表中项目的索引,请使用:

list.index(x)
Return the index in the list of the first item whose value is x. 
It is an error if there is no such item.
Run Code Online (Sandbox Code Playgroud)

这对我来说似乎有点奇怪,如果找不到该项目会引发错误.我来自(Objective-C land),它返回一个NSNotFound枚举(它只是一个max int,表示找不到该项).

所以我做了一些丑陋的事情来解决这个问题:

index = 0
for item in self.items:
   if item.id == desired_id:
        return index
    index = index + 1
 return -1
Run Code Online (Sandbox Code Playgroud)

我用-1来表示找不到该项目.有什么更好的方法可以做到这一点,为什么Python没有内置这样的东西?

python

24
推荐指数
3
解决办法
4万
查看次数

标签 统计

python ×3

list ×1

principles ×1