将带有两个参数的函数传递给python中的filter() [英] Passing a function with two arguments to filter() in python
问题描述
给出以下列表:
DNA_list = ['ATAT', 'GTGTACGT', 'AAAAGGTT']
我想过滤长度超过3个字符的字符串.我使用以下代码实现了这一点:
I want to filter strings longer than 3 characters. I achieve this with the following code:
具有for循环:
long_dna = []
for element in DNA_list:
length = len(element)
if int(length) > 3:
long_dna.append(element)
print long_dna
但是我希望我的代码更通用,因此以后可以过滤任何长度的字符串,因此我使用了一个函数和for循环:
But I want my code to be more general, so I can later filter strings of any length, so I use a function and for loop:
def get_long(dna_seq, threshold):
return len(dna_seq) > threshold
long_dna_loop2 = []
for element in DNA_list:
if get_long(element, 3) is True:
long_dna_loop2.append(element)
print long_dna_loop2
我想使用filter()
实现相同的通用性,但是我无法实现.如果使用上述功能get_long()
,当与filter()
一起使用时,我根本无法将参数传递给它.只是不可能还是有办法解决吗?
I want to achieve the same generality using filter()
but I cannot achieve this. If I use the above function get_long()
, I simply cannot pass arguments to it when I use it with filter()
. Is it just not possible or is there a way around it?
针对特定情况,我的代码为filter()
My code with filter()
for the specific case:
def is_long(dna):
return len(dna) > 3
long_dna_filter = filter(is_long, DNA_list)
推荐答案
使用lambda
提供阈值,如下所示:
Use lambda
to provide the threshold, like this:
filter(lambda seq: get_long(seq, 3),
dna_list)
这篇关于将带有两个参数的函数传递给python中的filter()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!