需要尝试计算列表中的重复列表

时间:2012-11-16 04:50:02

标签: python

我试图计算列表中有多少重复列表。但它的工作原理与我只能在列表中计算重复元素的方式相同。我对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)

2 个答案:

答案 0 :(得分: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})
>>> 

Counter()是dict()的子类,因此所有字典方法仍然有用。

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

答案 1 :(得分:0)

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


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

这不是最好的,但有效。 因为list不可清除,所以我提供了一个字符串作为键。