2014-04-27 89 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