Reputation: 45
I'm have a list like this ['a1,b1,c1', 'a2,b2,c2', 'a3,b3,d3']
and I'm trying to either write a function or a for loop that will take each set up these numbers as inputs
so for example the first time it runs a=a1, b=b1, c=c1
, the second time it'll run a=a2, b=b2 c=c2
as inputs
I've seen a few threads using functions with asterisks like this some_func(*params)
but I don't see how to make it a loop that kind of takes a combination of inputs like how I wanted it to
or would using a dict be able to address and do this?
an example would be like (sorry not making it superr specific and concrete)
def apply(a, b, c):
x = something
y = something_else
(hello, there) = somefunction(x, y, size=a)
sky = anotherfunction(beta[1], put=b, call=c)
any help is appreciated, or if there has been a similar question before, happy for it to be linked
Upvotes: 0
Views: 649
Reputation: 536
Suppose you have a list strings
and function func
strings = ['a1,b1,c1', 'a2,b2,c2', 'a3,b3,d3']
def func(a, b, c):
# your function
pass
Structure will be
for string in string:
func(*map(int, string.split(",")))
the map(int, string.split(","))
will split string and make a list like [1, 2, 3]
for '1,2,3'
.
Then the *
symbol will spread the numbers one for each parameter, for list [1, 2, 3]
will call the function like func(a=1, b=2, c=3)
.
Upvotes: 1
Reputation: 61910
If I understood correctly, use variadic arguments as follows:
def fun(*args):
"""Toy function"""
return sum(args) + 10
arguments = ["1,2,3", "1,5,6"]
for argument in arguments:
res = fun(*map(int, argument.split(",")))
print(res)
Output
16
22
The expression:
map(int, argument.split(","))
creates an iterable of integers from the argument
string. The *
unpacks these arguments.
Upvotes: 1