简体   繁体   English

如何使用filter()获取过滤数据的位置而不是值?

[英]How to use filter() to get the location of the filtered data instead of the value?

I am trying to build a graphics generator function that requires the location of data in the list I want to use the built-in filter function of python to get a list of the locations of the relevant data instead of their values. 我正在尝试构建一个图形生成器函数,该函数需要列表中数据的位置。我想使用python的内置过滤器功能来获取相关数据的位置列表,而不是其值。 Is it possible to do that? 有可能这样做吗?

I understand there are other methods to achieve this but is it at all possible to do this using the Filter() function? 我知道还有其他方法可以实现此目的,但是使用Filter()函数是否完全可以做到这一点?

You can use enumerate to turn your list into a list of two-item tuples, with the first item of each tuple being the location (we usually call it the position, or index) of the item, and the second item being the item in the original list at that position. 您可以使用enumerate将列表变成两个项目的元组列表,每个元组的第一项是项目的位置(我们通常称其为位置或索引),第二项是项目中的项该位置的原始列表。

The following code filters a list of [4, 1, 3, 5, 3] for items with value greater than 3 and returns the positions of such items. 以下代码过滤值大于3的项目的[4, 1, 3, 5, 3] 4、1、3、5、3]列表,并返回这些项目的位置。

a = [4, 1, 3, 5, 3]
print(list(map(lambda i: i[0], filter(lambda i: i[1] > 3, enumerate(a)))))

This outputs: 输出:

[0, 3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM