返回可变数量输出的python函数 [英] python function that returns a variable number of outputs
问题描述
我想输入一个未知宽度(列数)的表格,并且我希望我的函数为每列输出一个列表.我还输出了一个包含上述列表名称的列表.
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.
我正在尝试:
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))
当我知道我将输出多少列/列表(返回标题、a、b、c、d)时,该函数有效,但我试图概括的方式不起作用.
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)}
这篇关于返回可变数量输出的python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!