9

リストがあります:

hello = ['1', '1', '2', '1', '2', '2', '7']

リストの最も一般的な要素を表示したかったので、次を使用しました。

m = max(set(hello), key=hello.count)

ただし、上記のリストの 1 と 2 のように、同じ頻度で発生するリストの 2 つの要素が存在する可能性があることに気付きました。Max は、最大周波数要素の​​最初のインスタンスのみを出力します。

リストをチェックして、2 つの要素の両方が最大数のインスタンスを持っているかどうかを確認し、そうであれば両方を出力できるのは、どのようなコマンドですか? 私はここで途方に暮れています。

4

3 に答える 3

13

現在と同様のアプローチを使用すると、最初に最大数を見つけてから、その数を持つすべてのアイテムを探します。

>>> m = max(map(hello.count, hello))
>>> set(x for x in hello if hello.count(x) == m)
set(['1', '2'])

別の方法として、niceCounterクラスを使用することもできます。これを使用すると、効率的にカウントできます。

>>> hello = ['1', '1', '2', '1', '2', '2', '7']
>>> from collections import Counter
>>> c = Counter(hello)
>>> c
Counter({'1': 3, '2': 3, '7': 1})
>>> common = c.most_common()
>>> common
[('1', 3), ('2', 3), ('7', 1)]

次に、リスト内包表記を使用して、最大数を持つすべてのアイテムを取得できます。

>>> set(x for x, count in common if count == common[0][1])
set(['1', '2'])
于 2012-04-01T01:09:45.490 に答える
3

編集:変更されたソリューション

>>> from collections import Counter
>>> from itertools import groupby
>>> hello = ['1', '1', '2', '1', '2', '2', '7']
>>> max_count, max_nums = next(groupby(Counter(hello).most_common(),
                               lambda x: x[1]))
>>> print [num for num, count in max_nums]
['1', '2']
于 2012-04-01T02:15:07.930 に答える
2
from collections import Counter

def myFunction(myDict):
    myMax = 0 # Keep track of the max frequence
    myResult = [] # A list for return

    for key in myDict:
        print('The key is', key, ', The count is', myDict[key])
        print('My max is:', myMax)
        # Finding out the max frequence
        if myDict[key] >= myMax:
            if myDict[key] == myMax:
                myMax = myDict[key]
                myResult.append(key)
            # Case when it is greater than, we will delete and append
            else:
                myMax = myDict[key]
                del myResult[:]
                myResult.append(key)
    return myResult

foo = ['1', '1', '5', '2', '1', '6', '7', '10', '2', '2']
myCount = Counter(foo)
print(myCount)

print(myFunction(myCount))

出力:

The list: ['1', '1', '5', '2', '1', '6', '7', '10', '2', '2']
Counter({'1': 3, '2': 3, '10': 1, '5': 1, '7': 1, '6': 1})
The key is 10 , The count is 1
My max is: 0
The key is 1 , The count is 3
My max is: 1
The key is 2 , The count is 3
My max is: 3
The key is 5 , The count is 1
My max is: 3
The key is 7 , The count is 1
My max is: 3
The key is 6 , The count is 1
My max is: 3
['1', '2']

この簡単なプログラムを書きましたが、これもうまくいくと思います。most_common()検索するまで機能に気づきませんでした。これは、存在する最も頻繁な要素を返すと思います。最大頻度の要素を比較することで機能します。より頻繁な要素が表示されると、結果リストが削除され、一度追加されます。または、同じ周波数の場合は、単純に追加します。そして、カウンター全体が繰り返されるまで続けます。

于 2012-04-01T01:43:44.213 に答える