我有一个看起来像这样的元组列表。
[(1,2),(3,4),(2,1),(1,2),(2,3),(2,3)]
我希望输出看起来像这样。
[(1,2,2),(3,4,1),(2,1,1),(2,3,2)]
元组中的第三个值是元组在列表中出现的次数。
迭代元组列表并在元组结尾处添加值的有效方法是什么? 谢谢。
答案 0 :(得分:5)
data = [(1, 2), (3, 4), (2, 1), (1, 2), (2, 3), (2, 3)]
from collections import Counter, OrderedDict
# Use Counter to find the number of times the tuple occured
d = Counter(data)
# Use OrderedDict to maintain the order of occurance
# Get tuples from OrderedDict and get count from d, create a new tuple
print [item + (d[item],) for item in OrderedDict.fromkeys(data)]
# [(1, 2, 2), (3, 4, 1), (2, 1, 1), (2, 3, 2)]
答案 1 :(得分:1)
这是正确的代码:
>>> lst = [(1,2), (3,4), (2,1), (1,2), (2,3), (2,3)]
>>> def count(tuple, list):
... num = 0
... for k in list:
... if sorted(k) == sorted(tuple):
... num+=1
... return num
...
>>> count((1, 2), lst)
3
>>> newlst = []
>>> for k in lst:
... num = count(k, lst)
... new = k+(num,)
... if new not in newlst:
... newlst.append(new)
...
>>> newlst
[(1, 2, 3), (3, 4, 1), (2, 1, 3), (2, 3, 2)]
>>>
答案 2 :(得分:0)
我用一套来确定所有唯一的条目。然后我遍历集合中的每个项目并计算原始列表中该元组的出现次数,并创建一个新的元组,其中原始元组与计数结合。
>>> data = [(1,2),(3,4),(2,1),(1,2),(2,3),(2,3)]
>>> unique = set(data)
>>> count = [t + (data.count(t),) for t in unique]
>>> count
[(1, 2, 2), (2, 3, 2), (3, 4, 1), (2, 1, 1)]