简体   繁体   中英

Passing arbitrary number of arguments from list into function?

I have a function, that takes an input, then an *arg containing a sequence of two-element tuples. I also have an SQL command that generates a list of such tuples depending on what's in my database. That all works well, but I have no idea how to pass these tuples into the function.

I've tried assembling code as a string then executing it with exec(), which is sloppy anyway, but doesn't even work because the return() value within the function (containing the output I need) is ignored by the exec(). I've tried eval() which doesn't work because the function being called has inputs and other such actual code which eval doesn't handle; it only evaluates expressions. I don't think I can just call the function on the list of tuples directly, because that would be counted as just one argument instead of the (in this specific example) three, wouldn't it?

So how should I pass this list of tuples into my function, if I had:

TupleList = [('a','b'),('c','d'),('e','f')]
Func(Argument1, *Args)

And I want to call:

Func('ConstantValue',('a','b'),('c','d'),('e','f'))

while still retaining the return() of Func()?

def foo(arg1, *args):
    print(arg1)
    for arg in args:
        print(arg)

spam = [('a', 'b'), ('c', 'd'), ('e', 'f')]

foo('ConstantValue', *spam)

# or which yield same result
foo('ConstantValue', ('a', 'b'), ('c', 'd'), ('e', 'f'))

output

ConstantValue
('a', 'b')
('c', 'd')
('e', 'f')
ConstantValue
('a', 'b')
('c', 'd')
('e', 'f')
>>>

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