0

我试图计算列表中有多少重复列表。但它的工作方式与我可以在一个列表中计算重复元素的方式不同。我对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)
4

2 回答 2

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
>>> 
于 2012-11-16T06:40:44.843 回答
0
>>> dictt = {}
>>> for i in x:
    dictt[str(set(i))] = dictt.get(str(set(i)),0) + 1


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

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

于 2012-11-16T04:58:20.913 回答