2013-08-19 62 views
0

我有一個問題,轉化率從這樣的:轉換,列出保留元素

Counter({('pintor', 'NCMS000'): 1, ('ser', 'VSIS3S0'): 1, ('muralista', 'AQ0CS0'): 1, ('diego_rivera', 'NP00000'): 1, ('frida_kahlo', 'NP00000'): 1, ('caso', 'NCMS000'): 1}) 

也就是從這個代碼獲得:

res = collections.Counter(map(tuple, listaPalabras)) return res 

但我需要的是在這個名單形式:

[['pintor', 'NCMS000', 1], ['ser', 'VSIS3S0', 1], ['muralista', 'AQ0CS0', 1], ['diego_rivera', 'NP00000', 1], ['frida_kahlo', 'NP00000', 1], ('caso', 'NCMS000', 1]] 

回答

1

遍歷與列表理解計數器:

[list(k) + [v] for k, v in res.iteritems()] 

演示:

>>> from collections import Counter 
>>> res = Counter({('pintor', 'NCMS000'): 1, ('ser', 'VSIS3S0'): 1, ('muralista', 'AQ0CS0'): 1, ('diego_rivera', 'NP00000'): 1, ('frida_kahlo', 'NP00000'): 1, ('caso', 'NCMS000'): 1}) 
>>> [list(k) + [v] for k, v in res.iteritems()] 
[['pintor', 'NCMS000', 1], ['ser', 'VSIS3S0', 1], ['diego_rivera', 'NP00000', 1], ['frida_kahlo', 'NP00000', 1], ['muralista', 'AQ0CS0', 1], ['caso', 'NCMS000', 1]] 

如果你想在排序順序列出你的價值觀,用.most_common(),而不是.iteritems()

1
>>> from collections import Counter 
>>> c = Counter({('pintor', 'NCMS000'): 1, ('ser', 'VSIS3S0'): 1, ('muralista', 'AQ0CS0'): 1, ('diego_rivera', 'NP00000'): 1, ('frida_kahlo', 'NP00000'): 1, ('caso', 'NCMS000'): 1}) 
>>> [[key[0], key[1], value] for key, value in c.iteritems()] 
[['pintor', 'NCMS000', 1], ['ser', 'VSIS3S0', 1], ['diego_rivera', 'NP00000', 1], ['frida_kahlo', 'NP00000', 1], ['muralista', 'AQ0CS0', 1], ['caso', 'NCMS000', 1]] 

代碼使用list comprehension通過使用iteritems()遍歷Counter項(鍵和值)來構造一個列表的列表。由於您的案例中的每個鍵都是長度爲2的元組,因此它會按索引獲取元組的每個部分:key[0]key[1]

+0

你能也許有些話來解釋的代碼或你的方法添加到OP ? – theJollySin

+1

@theJollySin好點,補充說明一下。謝謝! – alecxe

+0

感謝所有的答案,還有一件事:我需要減去最後一個元素,並構建一個像[1,1,1,...]的向量。我有這個功能:###### def vectores(lista): r = [] for e列表中: r.append(e [1]) return r ########並給我[1]。我能做什麼? – JPP

1
>>> data = Counter({('pintor', 'NCMS000'): 1, ('ser', 'VSIS3S0'): 1, ('muralista', 'AQ0CS0'): 1, ('diego_rivera', 'NP00000'): 1, ('frida_kahlo', 'NP00000'): 1, ('caso', 'NCMS000'): 1}) 
>>> [[k[0], k[1], v] for k, v in data.items()] 
[['pintor', 'NCMS000', 1], ['ser', 'VSIS3S0', 1], ['diego_rivera', 'NP00000', 1], ['frida_kahlo', 'NP00000', 1], ['muralista', 'AQ0CS0', 1], ['caso', 'NCMS000', 1]] 

或替代使用的元組拆包:

>>> [[a, b, v] for (a, b), v in data.items()] 
[['pintor', 'NCMS000', 1], ['ser', 'VSIS3S0', 1], ['diego_rivera', 'NP00000', 1], ['frida_kahlo', 'NP00000', 1], ['muralista', 'AQ0CS0', 1], ['caso', 'NCMS000', 1]] 
1

你想是這樣的:

[[i, j, k] for ((i, j), k) in res.items()]