I want to input a table of unknown width (number of columns) and I want my function to output a list for each column. I am also outputting a list containing the names of the said lists.
I am trying this:
def crazy_fn(table):
titles=read_col_headers(table)
for i in range(1,len(table)):
for j in range(0,len(titles)):
vars()[titles[j]].append(table[i][j])
return titles, vars()[titles[k]] for k in range(0,len(titles))
The function works for when I know how many columns/lists I will output (return titles, a, b, c, d), but the way I've tried to generalize is not working.
Python functions can return multiple variables. These variables can be stored in variables directly. A function is not required to return a variable, it can return zero, one, two or more variables. This is a unique property of Python, other programming languages such as C++ or Java do not support this by default.
The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-key worded, variable-length argument list. The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args.
In Python, there are two ways to define a function that can take a variable number of arguments. Different forms of this type are: Positional arguments. Keyword arguments.
A function is not restricted to return a variable, it can return zero, one, two or more values. This is the default property of python to return multiple values/variables which is not available in many other programming languages like C++ or Java.
It's generally a bad idea to have a non-constant number of variables returned from a function, because using it is confusing and error-prone.
Why don't you return a dictionary mapping title headers to the list?
def crazy_fn(table):
result=dict()
titles=read_col_headers(table)
for title in titles:
result[title]=VALUE(TITLE)
return result
This can be abbreviated using dictionary comprehension to:
def crazy_fn(table):
return {title : VALUE(TITLE) for title in read_col_headers(table)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With