您的代码几乎可以正常工作。正如其他人所提到的,列表不能用作字典键,但元组可以。解决方案是将每个列表变成一个元组。
>>> 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})
>>>
Counter() 是 dict() 的子类,因此所有字典方法仍然有效。
>>> counter.keys()
[('coffee', 'cola', 'juice', 'tea'), ('cola', 'coffee', 'juice', 'tea')]
>>> k = counter.keys()[0]
>>> k
('coffee', 'cola', 'juice', 'tea')
>>> counter[k]
2
>>>