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

博客内容讲述了如何使用Python的for循环和函数来过滤DNA序列列表中长度超过3个字符的字符串。作者首先展示了使用for循环实现的方法,然后通过定义函数get_long实现了通用性。接着尝试使用filter函数,但遇到无法传递参数的问题。最后,解决方案是利用lambda表达式在filter函数中传入动态阈值。
摘要由CSDN通过智能技术生成

1586010002-jmsa.png

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、付费专栏及课程。

余额充值