+ 1
Represent function arguments in single structure.
I like to pass argument to a function random.choices It takes argument samples, weights and number of item as k. I have my samples as [ 'red', 'black', 'green'] and weights = [18,18,2]. So I like to assign arguments = ( samples, weights, k=100) and then random.choices(arguments). What is the proper way to represent data structure for arguments as tuple or list does not work. .
2 odpowiedzi
0
Look at the starred expression, it's gonna help you a lot.
Here is a simple example :
def func(a, b) :
return a + b
args = (1, 3)
print(func(*args))
I hope you understand this code snippet (I don't really want to explain in detail, since the subject is very wide).
[Edit]
You will have to care about three types of arguments : positional arguments, optional arguments and keyword-only argument.
def func(a, /, b=5, *, c=3):
pass
- a => positional argument
- b => positional optional argument
- c => keyword-only argument
You can call this functions like this :
- func(1)
- func(1, 2)
- func(1, 2, c=3)
- func(1, b=2, c=3)
But not like this :
- func(1, 2, 3)
0
Théophile. Appreciate the answer.
Sorry I still fail to understand.
The real question is how do I do args = ( 1, 3, c=2) and do func(*args).
Here c is an optional parameter to the function and pass as such. Think about sorted function where you pass key as an optional parameter. I like to capture this in args. Think that we are also providing name of the optional argument besides its value.