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.
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)}
Woah, too many loops
something like:
def crazy_fn(table):
titles = read_col_headers(table)
columns = zip(*table[1:])
return titles, columns
would probably do it. It's worth reading more about how python built in functions work.
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.