0

2 つのリストがtokens_e_setありtokens_f_set、2 つのすべての要素のすべての可能な組み合わせをディクショナリのキーとしてマップしたいとしますt_e_f。これらのキーはすべて、 の値も持っている必要があります1/len(tokens_e_set)。非常に長いトークンのリストを処理する必要があるため、最速の方法でそれを行う方法を探していました。コードは次のとおりです。

init_value=1/len(tokens_e_set)
t_e_f=collection.defaultdict(float)
for word_e in tokens_e_set:
    for word_f in tokens_f_set:
        t_e_f[(word_e,word_f)]=init_value

ありがとうございました!

4

2 に答える 2

0

比較タイミング:

C:\Python27>python lib\timeit.py -s "tokens_e_set=tokens_f_set=range(100)" -s "import collections" "t_e_f=collections.defaultdict(float);init_value=1/len(tokens_e_set)" "for word_e in tokens_e_set:" " for word_f in tokens_f_set:" "  t_e_f[word_e,word_f]=init_value"
100 loops, best of 3: 2.61 msec per loop

C:\Python27>python lib\timeit.py -s "tokens_e_set=tokens_f_set=range(100)" -s "from itertools import product" "t_e_f = dict.fromkeys(product(tokens_e_set,tokens_f_set),1.0/len(tokens_e_set))"
1000 loops, best of 3: 1.88 msec per loop

質問者の演習として、これらのスケールがどのように残っているか。

于 2013-02-01T16:03:45.130 に答える
0

productネストされた for ループの代わりに使用します。

すべて同じ値を持つ多くのキーを持つ辞書を初期化しているのでdict.fromkeys、最善の方法と思われます。

from itertools import product
t_e_f = dict.fromkeys(product(tokens_e_set,tokens_f_set),1.0/len(tokens_e_set))

(比較のタイミングは OP の演習として残されています。)

于 2013-02-01T15:08:14.213 に答える