我需要编写一个函数 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、exceptblock 。
代码:
>>> 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
>>>
