简体   繁体   中英

Multipy mutli parameters in Python

I am a begineer of python.

I want multipy multi arguements like this:

def multiply(*args):
    for nums in args
        return (args*args)

print(multiply(3, 4, 5))
60

EDIT: Actualy i want to make one again for substraction

python    
minus(3, 4, 7)
    6
def multiply(*args):
    n = 1
    for nums in args:
        n *= nums
    return n

print(multiply(3, 4, 5))
60

You can do this in a single line using functools.reduce and operator.mul , but we'll leave that for a later lesson.

You can use functools.reduce

from functools import reduce
def multiply(*args):
    return reduce(lambda a, b: a*b, args, 1) 

edit:

It turns out there is something even simpler starting in python 3.8:

from math import prod
def multiply(*args):
    return prod(args) 

There you go

def multiply(*args):
    x = 1
    for e in args:
        x = x*e
    return x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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