除了@阿維納什的答案,我建議使用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
邏輯並不總是更有效
做**沒有**編輯您的問題,要求新的o嗯,一旦你吸引了答案。相反,問一個新問題。 – Matt