2012-11-16 53 views
1

我試圖計算列表中有多少重複列表。但它的工作方式與我只能列表中的重複元素相同。我相當新的python,所以如果聽起來太容易道歉。需要嘗試和統計列表中的重複列表

這是我做過什麼

x= [["coffee", "cola", "juice" "tea" ],["coffee", "cola", "juice" "tea"] 
["cola", "coffee", "juice" "tea" ]] 
dictt= {} 

for item in x: 

    dictt[item]= dictt.get(item, 0) +1 

return(dictt) 
+0

你使用的字典是什麼? –

+0

你能向我們解釋你想達到的目標嗎?也許一些示例輸入_and_示例結果? – Tadeck

+0

閱讀本文http://docs.python.org/2/tutorial/datastructures.html#dictionaries - 列表不能用作鍵 - 您可以修改爲使用其他類型的鍵,如元組 –

回答

0
>>> dictt = {} 
>>> for i in x: 
    dictt[str(set(i))] = dictt.get(str(set(i)),0) + 1 


>>> dictt 
{"set(['coffee', 'juicetea', 'cola'])": 3} 

這是不是最好的,但工程。 因爲列表不可散列,所以我提供了一個字符串作爲鍵。

2

您的代碼差不多的作品。正如其他人所說,列表不能是 用作字典鍵,但元組可以。 解決方案是將每個列表變成一個元組。

>>> x= [["coffee", "cola", "juice", "tea"], ### <-- this list appears twice 
...  ["coffee", "cola", "juice", "tea"], 
...  ["cola", "coffee", "juice", "tea"]] ### <-- this list appears once 
>>> 
>>> dictt= {} 
>>> 
>>> for item in x: 
...  # turn the list into a tuple 
...  key = tuple(item) 
... 
...  # use the tuple as the dictionary key 
...  # get the current count for this key or 0 if the key does not yet exist 
...  # then increment the count 
...  dictt[key]= dictt.get(key, 0) + 1 
... 
>>> dictt 
{('cola', 'coffee', 'juice', 'tea'): 1, ('coffee', 'cola', 'juice', 'tea'): 2} 
>>> 

如果需要,您可以將元組變回列表。

>>> for key in dictt: 
...  print list(key), 'appears ', dictt[key], 'times' 
... 
['cola', 'coffee', 'juice', 'tea'] appears 1 times 
['coffee', 'cola', 'juice', 'tea'] appears 2 times 
>>> 

另外,Python有一個專門用於計算事物的collections.Counter()類。 (注意:您仍然需要把列表變成元組))

>>> from collections import Counter 
>>> counter = Counter() 
>>> for item in x: 
... counter[tuple(item)] += 1 
... 
>>> counter 
Counter({('coffee', 'cola', 'juice', 'tea'): 2, ('cola', 'coffee', 'juice', 'tea'): 1}) 
>>> 

計數器(是的dict()的一個子類,所以所有的字典方法仍然有效。

>>> counter.keys() 
[('coffee', 'cola', 'juice', 'tea'), ('cola', 'coffee', 'juice', 'tea')] 
>>> k = counter.keys()[0] 
>>> k 
('coffee', 'cola', 'juice', 'tea') 
>>> counter[k] 
2 
>>>