2

ロト (宝くじ) のクーポンがあります。

coupons = [[1,4,7,34,45,67], [2,8,16,34,35,38] ... ]

結果:

result = [7,12,13,26,29,34]

クーポンの当選番号を 1 行でカウントするにはどうすればよいですか? たとえば、次のような統計を返したいと思います。

statistics = [20, 15, 11, 1, 0, 0, 0]

どこ

statistics[0] - 当選番号が 0 のクーポンの金額、

統計[1] - 当選番号が 1 つのクーポンの金額、

統計[2] - 当選番号が 2 つのクーポンの金額、

統計[3] - 当選番号が 3 つのクーポンの金額、

統計[4] - 当選番号が 4 つのクーポンの金額、

統計[5] - 当選番号が 5 つのクーポンの金額、

統計[6] - 当選番号が 6 つのクーポンの金額

4

6 に答える 6

2

これを試して:

from collections import Counter

coupons = [[1,4,7,34,45,67]  , [2,8,16,34,35,38],
           [7,12,13,26,29,34], [1,2,3,4,5,6]]
result  = [7,12,13,26,29,34]

answer = Counter([6-len(set(result)-set(s)) for s in coupons])

最後の行は、要求されたワンライナーです。これを機能させるには、内部で使用されるデータ構造を変更する必要があったことに注意してください。クーポンと結果の両方がセットで表され、結果はCounter(特別な種類の辞書) に格納されますが、すべての答えは実用的な目的は、配列として動作します。

answer[0]
> 1

...

answer[6]
> 1

アップデート

OK、実際のリストへの変換を 1 行にまとめることができました。それ効率的ではありません (上記の最初のソリューションを使用する方が良いでしょう) が、うまく機能し、1 行で表示されます。

[Counter([6-len(set(result)-set(s)) for s in coupons])[x] for x in xrange(7)]
于 2012-11-06T22:22:49.047 に答える
2

インポートを「1行」としてカウントしない場合、これにより結果が1行で生成されます。

>>> coupons = [[1,4,7,34,45,67], [2,8,16,34,35,38], [1,4,7,13,55],
               [7,12,13,26,29,19]]
>>> result = [7,12,13,26,29,34]
>>>
>>> import collections
>>> collections.Counter(len(set(c).intersection(set(result))) for c in coupons)
Counter({2: 2, 1: 1, 5: 1})
于 2012-11-06T22:21:04.030 に答える
1

以下がその仕事をします:

from collections import *
cnt = defaultdict(int, Counter(len(set(result) & set(c)) for c in coupons))
statistics = [cnt[n] for n in range(7)]

これは、3 つのステートメントをセミコロンで区切ることで簡単に 1 行にまとめることができます。

statisticsリストである必要がない場合は、呼び出しとdefaultdict()最後の行を削除して、Counterインスタンスを直接使用できます。

于 2012-11-06T22:20:56.087 に答える
0

numpy を使用する場合は簡単です (ただし、少し醜い):

coupon=np.random.randint(0,100,(50,6)) % 50 coupons with 6 numbers between 0-99
statistics=np.random.randint(0,100,(6,))

np.histogram(np.sum((coupon==statistics[0]) | (coupon==statistics[1]) | (coupon==statistics[2]) | (coupon==statistics[3]) | (coupon==statistics[4]) | (coupon==statistics[5]),1),bins=np.arange(0,7))
于 2012-11-06T22:21:42.187 に答える
0
coupons = [[1,4,7,34,45,67], [2,8,16,34,35,38] … ]
result = [7,12,13,26,29,34]

coupons/の数字の位置がresult問題にならない場合 (couponとは異なる位置にある場合でも、4 つの当選番号があるresult)、これは機能します (重複する数字がなく、そのような重複番号の発生頻度と一致する必要があります):

result = set(result)
statistics = [len([coupon for coupon in coupons if len(set(coupon).intersection(result))==i]) for i in range(len(result))]

ただし、これは非常に非効率的です (O(n^2))。辞書ベースのアプローチとソートをお勧めします。

def getStats:
    result = set(result)
    statistics = [0]*len(result)
    for coupon in coupons:
        statistics[len(set(coupon).intersection(result))] += 1
    return statistics
于 2012-11-06T22:27:45.233 に答える
0

最初に、宝くじと当選番号を指定して、適切なボックスを返す関数を作成します。つまり、あなたの例

ticket = [1,4,7,34,45,67]
result = [7,12,13,26,29,34]

2 を返します。

次に、チケットの配列全体を反復処理する関数を作成し、最初の関数の戻り値に基づいて適切な配列インデックスをインクリメントします。

編集:ああ、1行のコードですか、それとも1行の配列ですか?

于 2012-11-06T22:14:05.720 に答える