1

我有 n 个等长的列表,表示数据库行的值。数据非常复杂,因此我将在示例中提供简化值。

本质上,我想将这些列表 (a,b,c) 的值映射到一个字典,其中键是列表 (id) 的集合。

示例列表:

id = [1,1,1,2,2,2,3,3,3]
a = [1,2,3,4,5,6,7,8,9]
b = [10,11,12,13,14,15,16,17,18]
c = [20,21,22,23,24,25,26,27,28]

需要的字典输出:

{id:[[a],[b],[c]],...}

{'1':[[1,2,3],[10,11,12],[20,21,22]],'2':[[4,5,6],[13,14,15],[23,24,25]],'3':[[7,8,9],[16,17,18],[26,27,28]]}

字典现在具有原始 a、b、c 中的值的列表列表,该列表由 id 列表中的唯一值子集,该列表现在是字典键。

我希望这足够清楚。

4

2 回答 2

1

尝试这个:

id = ['1','1','1','2','2','2','3','3','3']
a  = [1,2,3,4,5,6,7,8,9]
b  = [10,11,12,13,14,15,16,17,18]
c  = [20,21,22,23,24,25,26,27,28]

from collections import defaultdict
d = defaultdict(list)

# add as many lists as needed, here n == 3
lsts = [a, b, c]

for ki, kl in zip(id, zip(*lsts)):
    d[ki] += [kl]

for k, v in d.items():
    # if you don't mind using tuples, simply do this: d[k] = zip(*v)
    d[k] = map(list, zip(*v))

根据问题,结果完全符合预期:

d == {'1':[[1,2,3],[10,11,12],[20,21,22]],
      '2':[[4,5,6],[13,14,15],[23,24,25]],
      '3':[[7,8,9],[16,17,18],[26,27,28]]}
=> True
于 2013-08-21T22:54:09.280 回答
0
IDs = [1,1,1,2,2,2,3,3,3]
a = [1,2,3,4,5,6,7,8,9]
b = [10,11,12,13,14,15,16,17,18]
c = [20,21,22,23,24,25,26,27,28]

import itertools
d = {}
for key, group in itertools.groupby(sorted(zip(IDs, a, b, c)), key=lambda x:x[0]):
    d[key] = map(list, zip(*group)[1:])  # [1:] to get rid of the ID

print d

输出:

{1: [[1, 2, 3], [10, 11, 12], [20, 21, 22]], 
 2: [[4, 5, 6], [13, 14, 15], [23, 24, 25]], 
 3: [[7, 8, 9], [16, 17, 18], [26, 27, 28]]}
于 2013-08-21T22:55:03.830 回答