简体   繁体   English

如何忽略在python中接受多个参数的函数中的字符串?

[英]How do I ignore a string in a function that accepts multiple arguments in python?

I'm trying to answer a python programming question:我正在尝试回答一个 Python 编程问题:

Write a function operate_nums that computes the product of all other input arguments and returns its negative if the keyword argument negate (default False ) is True or just the product if negate is False .编写一个函数operate_nums ,计算所有其他输入参数的乘积,如果关键字参数negate (默认为False )为True则返回其负数,或者如果negateFalse则仅返回乘积。 The function should ignore non-numeric arguments.该函数应忽略非数字参数。

So far I have the following code:到目前为止,我有以下代码:

def operate_nums(*args):
     product = 1
     negate = True

     for i in args:
         product = product * i

     if negate == True:
         return product * -1
     return product

If I input a set of numbers and strings in my argument, how will code it so that my code ignores the strings?如果我在参数中输入一组数字和字符串,将如何对其进行编码,以便我的代码忽略这些字符串?

Use isinstance that lets you check the type of your variable.使用isinstance可让您检查变量的类型。 As pointed in one of the comments by @DarrylG, you can use Number as an indicator whether an argument is the one you want to multiply by正如@DarrylG 的评论之一所指出的,您可以使用Number作为参数是否是您要乘以的参数的指示符

from numbers import Number

def operate_nums(*args, negate=False):
    product = 1

    for arg in args:
        if isinstance(arg, Number): # check if the argument is numeric
            product = product * arg

    if negate == True:
            return product * -1

    return product

暂无
暂无

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

相关问题 Python:我如何找到/检查 function 接受哪种 arguments? - Python: How do I find / inspect what kind of arguments a function accepts? 如何将多个字符串 arguments 添加到我在 Python 中键入的 function? - How do I add multiple string arguments to my typing function in Python? 如何在python中使用字符串格式排列多个参数 - How do I arrange multiple arguments with string formatting in python 在 Python 中,如何注释接受固定参数的 function 以及任意数量的其他 arguments? - In Python, how do you annotate a function that accepts a fixed argument as well as any number of other arguments? Python类-如何创建一个接受未定义数量的参数的类? - Python Class - How do I create a class that accepts undefined number of arguments? 将接受多个 arguments 作为参数的 function 传递给 function - Pass a function that accepts multiple arguments as an argument to a function 如何从 Python 中的 function 对象列表中获取函数的全名和 arguments 作为字符串? - How do I get a function's full name and arguments as string from a list of function objects in Python? 如何编写一个接受字符串并返回字符串中特定字符总数的函数,而不使用 .count? - How do I write a function that accepts a string and will return a total number of certain characters in the string, without using .count? Python:将接受参数的函数传递给类方法? - Python: Pass a function that accepts arguments to a class method? 如何在 Python 格式字符串迷你语言中给出多个参数(宽度、叹息、分组)? - How do I give multiple arguments(width, sigh, grouping) in Python format string mini-language?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM