代码之家  ›  专栏  ›  技术社区  ›  panofish

如何在python中将整列附加到表(列表列表)中?

  •  1
  • panofish  · 技术社区  · 12 年前

    给定如下元组,这些元组是从mysql循环中的fetchall调用生成的。。。

    tuple1 = (('doug', 6), ('fred', 9), ('garth', 3))
    tuple2 = (('steve', 3), ('dan', 1))
    tuple3 = (('alan', 5), ('tom', 8), ('bob', 3), ('joe', 8))
    

    如何将每个元组作为一整列附加到这样的表(列表列表)中?

    table = [['doug',6,'steve',3,'alan',5],
             ['fred',9,'dan',1,'tom',8],
             ['garth',3,'',,'bob',3],
             ['',,'',,'joe',8]]
    
    1 回复  |  直到 12 年前
        1
  •  1
  •   Óscar López    12 年前

    由于列表的大小不同, zip() 在这里没有用处,所以我们必须实现我们自己的 zip -类似的函数,它接受不同长度的列表,用 None :

    def transpose(lists):
       if not lists: return []
       return map(lambda *row: list(row), *lists)
    

    接下来,将所有元组粘在一个列表中:

    tuple1 = (('doug', 6), ('fred', 9), ('garth', 3))
    tuple2 = (('steve', 3), ('dan', 1))
    tuple3 = (('alan', 5), ('tom', 8), ('bob', 3), ('joe', 8))
    tuples = [tuple1, tuple2, tuple3]
    

    现在答案很简单,用列表理解的方式写:

    table = [[y for x in t for y in x or ['']] for t in transpose(tuples)]
    

    结果如预期:

    table
    => [['doug', 6, 'steve', 3, 'alan', 5],
        ['fred', 9, 'dan', 1, 'tom', 8],
        ['garth', 3, '', 'bob', 3],
        ['', '', 'joe', 8]]
    

    关于评论中的问题:如何在现有表中添加新列?方法如下:

    def addcolumn(table, column):
        tr = transpose([table, column])
        return [(x if x else []) + (list(y) if y else []) for x, y in tr]
    

    继续示例:

    tuple4 = (('hewey', 1), ('dewey', 2), ('louie', 3))
    addcolumn(table, tuple4)
    
    => [['doug', 6, 'steve', 3, 'alan', 5, 'hewey', 1],
        ['fred', 9, 'dan', 1, 'tom', 8, 'dewey', 2],
        ['garth', 3, '', 'bob', 3, 'louie', 3],
        ['', '', 'joe', 8]]