从字典转换为列出保留元素

时间:2013-08-19 21:42:21

标签: python

我从转换中遇到问题:

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

4 个答案:

答案 0 :(得分: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 :(得分: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通过使用Counter循环iteritems()个项目(包括键和值)来构建列表列表。由于您的案例中的每个键都是长度为2的元组 - 它通过索引获取元组的每个部分:key[0]key[1]

答案 2 :(得分: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]]

答案 3 :(得分:1)

你想要这样的东西:

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