简体   繁体   English

如何在函数和Lambda中使用.count()

[英]How to do use .count() in function and lambda

I am a beginner of python, thank you so much! 我是python的初学者,非常感谢!

function: 功能:

def count(c):
    return c.count(1)

count(1,1,1,11,1,12,1)

This function doesn't work, I want to create a function count how many 1 's? 该功能不起作用,我想创建一个功能计数多少个1

lambda: lambda:

counts = lambda m:count('m') 
counts('what is you name, my name is mammy!')

This lambda doesn't work, too. 此lambda也无效。 I want to create a lambda count how many 'm' 's? 我想创建一个lambda计数,多少个'm'

Just add a * in front of c to make it take all the leftover arguments and sets it to a list 只需在c前面添加* ,以使其接受所有剩余的参数并将其设置为list

def count(*c):
    return c.count(1)

count(1,1,1,11,1,12,1)

and the lambda function can be: lambda函数可以是:

counts = lambda m: m.count('m') 
counts('what is you name, my name is mammy!')

Your first example fails because you're passing multiple arguments, and it only accepts one (presumably a list ). 您的第一个示例失败,因为您传递了多个参数,并且仅接受一个参数(可能是list )。 One way to fix it would be to pass a list : 解决该问题的一种方法是传递list

def count(c):
    return c.count(1)

print(count([1,1,1,11,1,12,1]))  # 5

Another way to fix it is to allow multiple parameters but treat them as a list . 解决该问题的另一种方法是允许多个参数,但它们视为list Here's how you can do that: 这是您可以执行的操作:

def count(*c):
    return c.count(1)

print(count(1,1,1,11,1,12,1))  # 5

Your second example is missing a thing to call count on. 您的第二个示例缺少要count的东西。 Again, one possible fix: 同样,一种可能的解决方法:

counts = lambda x: x.count('m')
print(counts('what is you name, my name is mammy!'))  # 6

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

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