1

给定如下元组,这些元组是从循环中的 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]]
4

1 回答 1

1

因为列表的大小不同,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]]
于 2013-09-19T16:04:18.900 回答