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}

これは最善ではありませんが、機能します。リストはハッシュ可能ではないため、キーとして文字列を指定します。

于 2012-11-16T04:58:20.913 に答える