python 传递带参数的函数,将带有两个参数的函数传递给python中的filter()

Given the following list:

DNA_list = ['ATAT', 'GTGTACGT', 'AAAAGGTT']

I want to filter strings longer than 3 characters. I achieve this with the following code:

With for loop:

long_dna = []

for element in DNA_list:

length = len(element)

if int(length) > 3:

long_dna.append(element)

print long_dna

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

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?

My code with filter() for the specific case:

def is_long(dna):

return len(dna) > 3

long_dna_filter = filter(is_long, DNA_list)

解决方案

Use lambda to provide the threshold, like this:

filter(lambda seq: get_long(seq, 3),

dna_list)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值