14

次のように2つのリストがあります

x = ['a','a','b','c','b','a']

x = ['a','a','b','c','c','d']

これらの各リストで最も多く発生する値を見つけようとしています。これは私が試したものです。

def unique_values(output,input):
    for i in input:
        if i not in output:
            output.append(i)
k = []
for i in k:
    unique_values(k,x)
    y.remove(i)

ここまでたどり着きましたがfor i in k:、リスト内のすべての値を削除する前に停止する方法がわかりません。

4

2 に答える 2

36

You can use Counter module from collections, if you want to find the occurrences of each element in the list: -

>>> x = ['a','a','b','c','c','d']

>>> from collections import Counter
>>> count = Counter(x)
>>> count
Counter({'a': 2, 'c': 2, 'b': 1, 'd': 1})
>>> count.most_common()
[('a', 2), ('c', 2), ('b', 1), ('d', 1)]

So, the first two elements are most common in your list.

>>> count.most_common()[0]
('a', 2)
>>> count.most_common()[1]
('c', 2)

or, you also pass parameter to most_common() to specify how many most-common elements you want: -

>>> count.most_common(2)
[('a', 2), ('c', 2)]

Update : -

You can also find out the max count first, and then find total number of elements with that value, and then you can use it as parameter in most_common(): -

>>> freq_list = count.values()
>>> freq_list
[2, 2, 1, 1]
>>> max_cnt = max(freq_list)
>>> total = freq_list.count(max_cnt)

>>> most_common = count.most_common(total)
[('a', 2), ('c', 2)]

>>> [elem[0] for elem in most_common]
['a', 'c']
于 2012-12-04T16:35:49.443 に答える
0

別の解決策は次のとおりです。

max(zip((x.count(item) for item in set(x)), set(x)))

まず、set を使用して重複要素を含まないコレクションを取得します。

>>> set(x)
{'a', 'c', 'b'}

次に、各要素が x に含まれる回数を数えます。これはジェネレーターオブジェクトを返します。値を表示するリストにすることができます ("( ... )" の代わりに "[ ... ]" を使用)。[3, 1, 2] が返されます。

>>> (x.count(item) for item in set(x))

次に、カウントを取得し、zip を使用して要素とペアにします。次のステップの最初の発生回数。list( ... ) を使用してその値を確認できます。[(3, 'a'), (1, 'c'), (2, 'b')] が返されます。

>>> zip((x.count(item) for item in set(x)), set(x))

最後に、max を使用してどのペアが最も頻繁に発生するかを見つけます。

>>> max(zip((x.count(item) for item in set(x)), set(x)))
(3, 'a')

2 番目の値に関しては、ソリューションは少し長くなります。上記はリスト内包表記内で使用されます。

>>> [mitem for mitem in zip((x.count(item) for item in set(x)),set(x)) if mitem[0] == max((x.count(item) for item in set(x)))]
[(2, 'a'), (2, 'c')]
于 2012-12-04T17:27:57.740 に答える