2012-11-16 51 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 
>>>