Python:返回列表的第一个元素的索引,这使得传递的函数为真 [英] Python: return the index of the first element of a list which makes a passed function true

查看:19
本文介绍了Python:返回列表的第一个元素的索引,这使得传递的函数为真的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

list.index(x) 函数返回列表中第一个值为 x 的项目的索引.

有没有一个函数,list_func_index(),类似于index()函数,有一个函数,f(),如一个参数.函数 f() 对列表的每个元素 e 运行,直到 f(e) 返回 True.然后list_func_index()返回e的索引.

代码方面:

<预><代码>>>>def list_func_index(lst, func):对于范围内的 i(len(lst)):如果函数(lst [i]):返回我raise ValueError('没有元素使 func True')>>>l = [8,10,4,5,7]>>>def is_odd(x): 返回 x % 2 != 0>>>list_func_index(l,is_odd)3

有更优雅的解决方案吗?(以及更好的函数名称)

解决方案

您可以使用生成器在单行中做到这一点:

next(i for i,v in enumerate(l) if is_odd(v))

生成器的好处是它们只计算请求的数量.所以请求前两个索引(几乎)同样简单:

y = (i for i,v in enumerate(l) if is_odd(v))x1 = 下一个(y)x2 = 下一个(y)

不过,在最后一个索引之后会出现 StopIteration 异常(这就是生成器的工作方式).这在您的优先"方法中也很方便,因为要知道没有找到这样的值 --- list.index() 函数会在此处抛出 ValueError.

The list.index(x) function returns the index in the list of the first item whose value is x.

Is there a function, list_func_index(), similar to the index() function that has a function, f(), as a parameter. The function, f() is run on every element, e, of the list until f(e) returns True. Then list_func_index() returns the index of e.

Codewise:

>>> def list_func_index(lst, func):
      for i in range(len(lst)):
        if func(lst[i]):
          return i
      raise ValueError('no element making func True')

>>> l = [8,10,4,5,7]
>>> def is_odd(x): return x % 2 != 0
>>> list_func_index(l,is_odd)
3

Is there a more elegant solution? (and a better name for the function)

解决方案

You could do that in a one-liner using generators:

next(i for i,v in enumerate(l) if is_odd(v))

The nice thing about generators is that they only compute up to the requested amount. So requesting the first two indices is (almost) just as easy:

y = (i for i,v in enumerate(l) if is_odd(v))
x1 = next(y)
x2 = next(y)

Though, expect a StopIteration exception after the last index (that is how generators work). This is also convenient in your "take-first" approach, to know that no such value was found --- the list.index() function would throw ValueError here.

这篇关于Python:返回列表的第一个元素的索引,这使得传递的函数为真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆