2015-09-19 91 views
1

我需要編寫一個函數ind(e,L),它包含一個列表L和一個元素e。函數ind()應該返回在L中首次找到e的索引。計數從0開始。如果e不是L的元素,則ind(e,L)應該返回等於len(L)的整數。返回在列表中首次找到元素的索引 - Python

這是我到目前爲止有:

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

有人可以幫我,因爲我不能看着辦吧!

+0

做**沒有**編輯您的問題,要求新的o嗯,一旦你吸引了答案。相反,問一個新問題。 – Matt

回答

3

您需要做一些更改。

  • 刪除大約在L附近的方括號。
  • 刪除e附近的引號,因爲e是一個變量而非值。
  • 添加try,except塊。

代碼:

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

這是低效的......'試試:返回L.index(e)除了ValueError:return len(L)'會更好。 – vaultah

+1

是的,你的代碼有2N的複雜性。編輯N – Pynchia

+1

@vaultah編輯.... –

3

除了@阿維納什的答案,我建議使用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邏輯並不總是更有效

0

或者說,不引入異常處理或呼喚Python的list.index方法:

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

    return index+1 
0

此代碼應工作:

def ind(e, L): 
    if e in L: 
     return L.index(e) 
    if e not in L: 
     return len (L) 
相關問題