您的代码差不多的作品。正如其他人所说,列表不能是 用作字典键,但元组可以。 解决方案是将每个列表变成一个元组。
>>> 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 - 列表不能用作键 - 您可以修改为使用其他类型的键,如元组 –