您的代碼差不多的作品。正如其他人所說,列表不能是 用作字典鍵,但元組可以。 解決方案是將每個列表變成一個元組。
>>> 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
>>>
你使用的字典是什麼? –
你能向我們解釋你想達到的目標嗎?也許一些示例輸入_and_示例結果? – Tadeck
閱讀本文http://docs.python.org/2/tutorial/datastructures.html#dictionaries - 列表不能用作鍵 - 您可以修改爲使用其他類型的鍵,如元組 –