对列表中的元组进行迭代,并为元组添加权重



我有一个元组列表,如下所示。

[(1,2),(3,4),(2,1),(1,2),(2,3),(2,3)]

我想要这样的输出。

[(1,2,2),(3,4,1),(2,1,1),(2,3,2)]

元组中的第三个值是元组在列表中出现的次数。

迭代元组列表并在元组末尾添加值的有效方法是什么?谢谢

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

以下是正确的代码:

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

我使用了一个集合来确定所有唯一的条目。然后,我遍历集合中的每个项,计算该元组在原始列表中的出现次数,并将原始元组与计数相结合,创建一个新的元组。

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

最新更新