2014-04-27 68 views
3

我有一个看起来像这样的元组列表。迭代列表中的元组并为元组添加权重

[(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

'(1,2)'只发生了两次。 – thefourtheye

+0

已更正。谢谢@thefourtheye – pravi

回答

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

工程太棒了!谢谢 – pravi

+0

@pravi很高兴有帮助。如果你觉得我的答案对你有帮助,你可以[接受我的答案](http://meta.stackoverflow.com/a/5235/192545):-) – thefourtheye

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

谢谢!有帮助的回答 – pravi

+0

你介意帮助你吗? –

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

如果列表很长,这将是低效的,因为'data.count'是一个O(N)操作。 – thefourtheye

+0

@thefourtheye谢谢。现在我已经了解了'collections'是如何工作的,当然'Counter'是专门针对所提出的问题而设计的。 –

+0

你是对的,'藏品'模块真棒。阅读更多关于:) – thefourtheye