返回可变数量输出的python函数

use*_*236 6 python python-2.7

我想输入一个未知宽度的表(列数),我希望我的函数输出每列的列表.我还输出一个包含所述列表名称的列表.

我在尝试这个:

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))
Run Code Online (Sandbox Code Playgroud)

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

Ada*_*tan 9

从函数返回非常数量的变量通常是个坏主意,因为使用它会让人感到困惑和容易出错.

为什么不返回将标题标题映射到列表的字典?

def crazy_fn(table):  
    result=dict()
    titles=read_col_headers(table)
    for title in titles:
        result[title]=VALUE(TITLE)
    return result
Run Code Online (Sandbox Code Playgroud)

这可以使用字典理解缩写为:

def crazy_fn(table):
   return {title : VALUE(TITLE) for title in read_col_headers(table)}
Run Code Online (Sandbox Code Playgroud)


She*_*hep 5

哇,太多的循环

就像是:

def crazy_fn(table): 
    titles = read_col_headers(table)
    columns = zip(*table[1:])
    return titles, columns
Run Code Online (Sandbox Code Playgroud)

可能会这样做.值得一读的是有关python内置函数的工作方式.