2013-08-21 69 views
1

我有n個表示數據庫行值的等長列表。數據非常複雜,所以我會在示例中提供簡化的值。將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列表。

我希望這已經夠清楚了。

+2

小心使用'id' - 這是一個python builtin。 – Brionius

回答

2

試試這個:

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 
1
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 

OUTPUT:

{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]]} 
+0

同樣正確。謝謝。 –

相關問題