3

table という名前の 2D マトリックスと count という名前のリストがあります。テーブルでは、データは各列のデータセットの数 count に格納されます。この場合、first_index は組み合わせの数を表示するだけで、588 の組み合わせ (7*6*2*7) があります。私のコードは静的なので、動的ループ/変数を作成する可能性が必要です。

テーブル:

[1, 30, 50, 60]
[2, 31, 51, 61]
[3, 32, 0, 62]
[4, 33, 0, 63]
[5, 34, 0, 64]
[6, 35, 0, 65]
[7, 0, 0, 66]

カウント:

[7, 6, 2, 7]

私の場合、コードは正常に機能しますが、4行以上あるかどうかは不明であるため、実際には適切なコードではありません。私はpythonの初心者です。この問題を解決する別の方法があるかもしれません

for k in range(count[0]):
    for kk in range(count[1]):
        for kkk in range(count[2]):
            for kkkk in range(count[3]):
                print('{0:3} , {1:3} , {2:1}'.format(first_index, table[k][0], 1))
                print( '{0:3} , {1:3} , {2:1}'.format(first_index, table[kk][1], 2))
                print( '{0:3} , {1:3} , {2:1}'.format(first_index, table[kkk][2], 3))
                print( '{0:3} , {1:3} , {2:1}'.format(first_index, table[kkkk][3], 4))
                print
                first_index+=1

出力は次のようになります

1 ,   1 , 1
1 ,  30 , 2
1 ,  50 , 3
1 ,  60 , 4

2 ,   1 , 1
2 ,  30 , 2
2 ,  50 , 3
2 ,  61 , 4

...

588 ,   7 , 1
588 ,  35 , 2
588 ,  51 , 3
588 ,  66 , 4
4

2 に答える 2

4

ここでは、itertools.product巧妙なロジックを使用しています。

from itertools import product

def special_combinations(table):
    for r in product(*zip(*table)):
        if 0 in r:
            continue
        yield r

count変数はまったく必要ありません。このソリューションの使用:

>>> table = [[1, 30, 50, 60],
             [2, 31, 51, 61],
             [3, 32,  0, 62],
             [4, 33,  0, 63],
             [5, 34,  0, 64],
             [6, 35,  0, 65],
             [7,  0,  0, 66]]
>>> for idx, val in enumerate(special_combinations(table)):
    print idx+1, val

1 (1, 30, 50, 60)
2 (1, 30, 50, 61)
3 (1, 30, 50, 62)
4 (1, 30, 50, 63)
5 (1, 30, 50, 64)
6 (1, 30, 50, 65)
7 (1, 30, 50, 66)
8 (1, 30, 51, 60)
9 (1, 30, 51, 61)
10 (1, 30, 51, 62)
...
584 (7, 35, 51, 62)
585 (7, 35, 51, 63)
586 (7, 35, 51, 64)
587 (7, 35, 51, 65)
588 (7, 35, 51, 66)

ボーナス: ワンライナー:

[(i+1, R) for i, R in enumerate(r for r in product(*zip(*table)) if not 0 in r)]

注: テーブルからゼロを削除すると、パフォーマンスが大幅に向上する可能性があります。

>>> table
[[1, 30, 50, 60], 
[2, 31, 51, 61], 
[3, 32, 0, 62], 
[4, 33, 0, 63], 
[5, 34, 0, 64], 
[6, 35, 0, 65], 
[7, 0, 0, 66]]
>>> table = [t[:t.index(0)] if 0 in t else t for t in map(list, zip(*table))]
>>> table
[[1, 2, 3, 4, 5, 6, 7], 
[30, 31, 32, 33, 34, 35], 
[50, 51], 
[60, 61, 62, 63, 64, 65, 66]]

そして、あなたの解決策ははるかに簡単です。

>>> [(i+1, R) for i, R in enumerate(r for r in product(*table))]
于 2013-08-21T13:10:24.810 に答える
1

ここでは、次を使用したソリューションに従いますitertools.product

from itertools import product
first_index=1
for i in product(*[range(i) for i in count]):
    for j in range(len(count)):
        print( '{0:3} , {1:3} , {2:1}'.format(first_index, table[i[j]][j], j+1))
    first_index += 1
于 2013-08-21T12:57:16.040 に答える