我有一个键/值对列表
我想成对计算唯一值
列表示例
[(12, 0), (10, 1), (11, 777), (11, 0) ,(10, 1)]
结果如下:
[(12, 0, 1), (10, 1 , 2), (11, 777, 1), (11, 0, 1)]
我尝试了地图操作,但没有成功 谢谢 !
答案 0 :(得分:3)
>>> from collections import Counter
>>>
>>> lst = [(12, 0), (10, 1), (11, 777), (11, 0) ,(10, 1)]
>>> [key + (cnt,) for key, cnt in Counter(lst).items()]
[(11, 0, 1), (11, 777, 1), (10, 1, 2), (12, 0, 1)]
答案 1 :(得分:2)
使用collections.Counter
:
>>> from collections import Counter
>>> a =[(12, 0), (10, 1), (11, 777), (11, 0) ,(10, 1)]
>>> [(*i,j) for (i,j) in Counter(a).items()]
# [(11, 0, 1), (11, 777, 1), (10, 1, 2), (12, 0, 1)]
>>> [i for i in Counter(a).items()]
# [((11, 0), 1), ((11, 777), 1), ((10, 1), 2), ((12, 0), 1)]
答案 2 :(得分:1)
这样的事情对你有用吗?
your_list = [(12, 0), (10, 1), (11, 777), (11, 0) ,(10, 1)]
result = [(a,b,your_list.count((a,b))) for (a,b) in your_list]
# [(12, 0, 1), (10, 1, 2), (11, 777, 1), (11, 0, 1), (10, 1, 2)]
如果您希望每个条目只出现一次
set(result)
# set([(12, 0, 1), (11, 0, 1), (11, 777, 1), (10, 1, 2)])
答案 3 :(得分:1)
您也可以使用内置map
方法,这样:
>>> l = [(12, 0), (10, 1), (11, 777), (11, 0) ,(10, 1)]
>>> result = []
>>> map(lambda s: result.append((s[0],s[1],l.count(s))), set(l))
[None, None, None, None]
>>> result
[(11, 0, 1), (11, 777, 1), (10, 1, 2), (12, 0, 1)]