2

itertools 関数にはエラーはありませんが、完了すると何も出力されません。私のコードは次のとおりです。

def comb(iterable, r):
    pool = tuple(iterable)
    n = len(pool)
    for indices in permutations(range(n), r):
        if sorted(indices) == list(indices):
            print (indices)
            yield tuple(pool[i] for i in indices)

print ステートメントを含めましたが、計算された合計の組み合わせが出力されません。

4

2 に答える 2

3

ジェネレーターの仕組みについて読む必要があります。呼び出すcomb()と、ジェネレーター オブジェクトが返されます。次に、ジェネレーター オブジェクトで何かを実行して、オブジェクトから返されるオブジェクトを取得する必要があります。

from itertools import permutations

lst = range(4)
result = list(comb(lst, 2))  # output of print statement is now shown

print(result) # prints: [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]

comb()ジェネレーター オブジェクトを返します。次に、それをlist()繰り返し、値をリストに収集します。反復時に、print ステートメントが起動します。

于 2012-04-18T03:02:05.843 に答える
1

ジェネレーターオブジェクトを返します。それを繰り返すと、印刷が表示されます。例えば:

for x in comb(range(3),2):
    print "Printing here:", x

あなたにあげる:

(0, 1) # due to print statement inside your function
Printing here: (0, 1)
(0, 2) # due to print statement inside your function
Printing here: (0, 2)
(1, 2) # due to print statement inside your function
Printing here: (1, 2)

したがって、組み合わせを 1 行ずつ出力したいだけの場合は、関数内の print ステートメントを削除し、リストに変換するか、それを反復処理します。これらを次のように 1 行ずつ印刷できます。

print "\n".join(map(str,comb(range(4),3)))

あなたにあげる

(0, 1, 2)
(0, 1, 3)
(0, 2, 3)
(1, 2, 3)
于 2012-04-18T03:00:07.413 に答える