如何在列表中创建列表列表

时间:2012-04-20 07:37:17

标签: python

我有列表列表,例如

res = [[None,'A','B'],[19980228, 'd1', 't1'],[19980302, 'd2', 't2'],[19980303, 'd3', 't3']]

现在我需要将上述结果构建为元组列表字典

{'A': [(19980228, 'd1'), (19980302, 'd2'), (19980303, 'd3')], 
 'B': [(19980228, 't1'), (19980302, 't2'), (19980303, 't3')]}

请让我知道这个概念,提前谢谢。

3 个答案:

答案 0 :(得分:2)

这应该这样做:

x, A, B = res[0]
output = {A:[], B:[]}
for a,b,c in res[1:]:
  output[A].append((a, b))
  output[B].append((a, c))

答案 1 :(得分:2)

>>> res = [[None,'A','B'],[19980228, 'd1', 't1'],[19980302, 'd2', 't2'],[19980303, 'd3', 't3']]
>>> {a:[(r[0], r[i]) for r in res[1:]] for i, a in enumerate(res[0]) if a}
{'A': [(19980228, 'd1'), (19980302, 'd2'), (19980303, 'd3')], 'B': [(19980228, 't1'), (19980302, 't2'), (19980303, 't3')]}

注意:正如@shuzOMGchen指出的那样,这需要在python 2.7和3.0中添加的“字典理解”,因此如果您使用的是早期版本,则必须稍微更改代码。这里没有使用字典理解(它非常难看,我只是试图从上面复制我的逻辑)

>>> res = [[None,'A','B'],[19980228, 'd1', 't1'],[19980302, 'd2', 't2'],[19980303, 'd3', 't3']]
>>> d = {}
>>> for i, a in enumerate(res[0]):
...     if a:
...         d[a] = [(r[0], r[i]) for r in res[1:]]
... 
>>> d
{'A': [(19980228, 'd1'), (19980302, 'd2'), (19980303, 'd3')], 'B': [(19980228, 't1'), (19980302, 't2'), (19980303, 't3')]}

答案 2 :(得分:0)

>>> res = [[None,'A','B'],[19980228, 'd1', 't1'],[19980302, 'd2', 't2'],[19980303, 'd3', 't3']]
>>> d = dict((x[0],x[1:]) for x in zip(*res))
>>> nums = d.pop(None)
>>> for key in d:
        d[key] = zip(nums,d[key])


>>> d
{'A': [(19980228, 'd1'), (19980302, 'd2'), (19980303, 'd3')], 'B': [(19980228, 't1'), (19980302, 't2'), (19980303, 't3')]}