简体   繁体   English

返回可变数量输出的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. 我还输出一个包含所述列表名称的列表。

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. 该函数适用于我知道将输出多少列/列表(返回标题,a,b,c,d),但我试图概括的方式不起作用。

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. 值得一读的是有关python内置函数的工作方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM