Skip to main content
 首页 » 编程设计

python之返回列表中首次找到元素的索引之Python

2025年05月04日14tuyile006

我需要编写一个函数 ind(e, L),它接受一个列表 L 和一个元素 e。函数 ind() 应返回在 L 中首次找到 e 的索引。计数从 0 开始。如果 e 不是 L 的元素,则 ind(e, L) 应返回等于 len(L) 的整数。

这是我目前所拥有的:

def ind(e, L): 
    if e in L: 
        return [L].index('e') 
    if e not in L:  
        return len[L] 

谁能帮帮我,因为我想不通!

请您参考如下方法:

你需要做一些改变。

  • 删除 L 周围的方括号。
  • 删除 e 周围的引号,因为 e 是变量而不是值。
  • 添加try、except block 。

代码:

>>> def ind(e, L): 
        try:  
            return L.index(e)  
        except ValueError:  
            return len(L) 
 
 
>>> ind(3, [1,2]) 
2 
>>> ind(3, [1,2,3,4,3]) 
2 
>>> ind('r', ['a']) 
1 
>>> ind('r', ['a', 'r']) 
1 
>>>