使用相同的表获取列表中的所有列

2024-09-29 23:19:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试检索每个表名的列列表

假设我有下表

('tableA', 'columnA', 1)
('tableA', 'columnB', 2)
('tableB', 'columnA', 1)
('tableB', 'columnB', 2)
('tableC', 'columnA', 1)
('tableD', 'columnA', 1)

如何返回按相同表名分组的列表? 所以它返回以下内容

('tableA', 'columnA', 'columnB')
('tableB', 'columnA', 'columnB')
('tableC', 'columnA')
('tableD', 'columnA')

Tags: 列表columnbcolumnatablebtableatablectabled
1条回答
网友
1楼 · 发布于 2024-09-29 23:19:36

你可以用^{}来做这个。请注意,这要求首先按表名对列表进行排序,但在您的情况下似乎是这样。否则,请先排序

get_data_from_table.sort() # only if not already sorted
tables = [[key] + [g[1] for g in groups] 
          for (key, groups) in itertools.groupby(get_data_from_table, 
                                                 key=operator.itemgetter(0))]

或者使用字典(或^{}),将表名映射到列:

d = collections.defaultdict(list)
for t, c, n in get_data_from_table:
    d[t].append(c)
tables = [[key] + values for key, values in d.items()]

相关问题 更多 >

    热门问题