python返回元素所在位置_返回在列表Python中第一次找到元素的索引

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的评论:

^{pr2}$

基准测试: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并不总是更有效

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值