2015-04-02 63 views

回答

3

試試這個:

l=[ ['A', 'C21'], ['A','D43'],['B','D34'],['C','D45'],['C','D56']] 
x = {} 

for a in l: 
    if a[0] not in x.keys(): 
     x[a[0]] = [a[1]] 
    else: 
     x[a[0]].append(a[1]) 

print x 

array_result = [] 
for keys, vals in x.iteritems(): 
    array_result.append([keys, ' '.join(vals)]) 

print array_result 
2

如果密鑰是連續的,那麼你可以使用itertools.groupby,如:

from itertools import groupby 

data =[ ['A', 'C21'], ['A','D43'],['B','D34'],['C','D45'],['C','D56'] ] 
new_data = [[k, ' '.join(el[1] for el in g)] for k, g in groupby(data, lambda L: L[0])] 
# [['A', 'C21 D43'], ['B', 'D34'], ['C', 'D45 D56']] 

如果不是和訂單其實並不重要,那麼:

from collections import defaultdict 

dd = defaultdict(list) 
for key, val in data: 
    dd[key].append(val) 

new_data = [[k, ' '.join(v)] for k,v in dd.items()] 
# [['B', 'D34'], ['C', 'D45 D56'], ['A', 'C21 D43']] 

或者 - 使用dict.setdefault,例如:

d = {} 
for key, val in data: 
    d.setdefault(key, []).append(val) 
new_data = [[k, ' '.join(v)] for k,v in d.items()] 

或者,如果密鑰是不連續的,但輸出應該保持輸入的順序,然後用collections.OrderedDict,如:

from collections import OrderedDict 

d = OrderedDict() 
for key, val in data: 
    d.setdefault(key, []).append(val) 

new_data = [[k, ' '.join(v)] for k,v in d.items()] 
# [['A', 'C21 D43'], ['B', 'D34'], ['C', 'D45 D56']] 
+0

感謝喬恩,PNV和Bhargav你的偉大的答案!我確實需要有序的輸出,所以可能會使用groupby或orderdict。 – user3843673 2015-04-03 04:04:58

+0

@ user3843673在Stack Overflow中,我們通過標記答案來表示感謝。請記住Jon的答案已被接受。看到這張圖片的參考 - http://i.stack.imgur.com/uqJeW.png和這篇文章爲您的理解http://meta.stackexchange.com/questions/5234/how-does-accepting-an-回答工作在你未來的工作中一切順利! – 2015-04-03 20:39:46