返回在列表中首次找到元素的索引 - Python

时间:2015-09-19 16:50:40

标签: python list indexing integer element

我需要编写一个函数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]

有人可以帮助我,因为我无法理解!

4 个答案:

答案 0 :(得分:3)

你需要做一些改变。

  • 删除L周围存在的方括号。
  • 删除e周围存在的引号,因为e是变量而不是值。
  • 添加tryexcept阻止。

代码:

>>> 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
>>> 

答案 1 :(得分:3)

除了@ Avinash的答案之外,我建议使用tenary conditional operator来简单说明一下:

In [25]: def ind(e, L):
    ...:     return L.index(e) if e in L else len(L)

In [26]: lst=[1,2]

In [27]: ind(2, lst)
Out[27]: 1

In [28]: ind(33, lst)
Out[28]: 2

或尝试@vaultah评论的内容:

In [43]: def ind2(e, L):
    ...:     try: 
    ...:         return L.index(e) 
    ...:     except ValueError: 
    ...:         return len(L)
    ...:     

基准:

In [65]: s='Python is a dynamic and strongly typed programming language that is designed to emphasize usability. Two similar but incompatible versions of Python are in widespread use (2 and 3). Please consider using [python-2.7] or [python-3.x] tags for version-specific questions about Python.'

In [66]: lst=list(s)

In [67]: %timeit ind('r', lst)
The slowest run took 6.81 times longer than the fastest. This could mean that an intermediate result is being cached 
1000000 loops, best of 3: 989 ns per loop

In [68]: %timeit ind2('r', lst)
The slowest run took 5.01 times longer than the fastest. This could mean that an intermediate result is being cached 
1000000 loops, best of 3: 640 ns per loop

In [69]: lst2=list(s.replace('r', '')) #remove all 'r's in the list

In [70]: %timeit ind('r', lst2)
100000 loops, best of 3: 3.77 µs per loop

In [71]: %timeit ind2('r', lst2)
The slowest run took 4.12 times longer than the fastest. This could mean that an intermediate result is being cached 
100000 loops, best of 3: 5.61 µs per loop

In [72]:

注意 try-except逻辑并不总是更有效

答案 2 :(得分:0)

或者,不引入异常处理或调用Python自己的list.index方法:

def ind(e, L):
    for index, item in enumerate(L):
        if item == e:
             return index

    return index+1

答案 3 :(得分:0)

此代码应该有效:

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