2017-10-11 9 views
1

引数として1つ以上のリストを受け入れ、それらのリストのデカルト積を重複排除形式で返す、Python 3.6コマンドラインプログラムを記述しようとしています。Pythonの任意の数の引数のデカルト積3.6

1つと2つのリスト引数で正常に動作しますが、3つ以上の引数を正しく処理する方法を理解できません。

出力は、コマンドラインで引数として渡されるすべてのリストを含むデカルト積です。

これは私がこれまで持っているコードです:

これを返す abc 123 defコマンドライン引数でプログラムを実行する
def createArgumentParser(): 

    from argparse import ArgumentParser 

    __parser = ArgumentParser() 
    __parser.add_argument("list", type=list, nargs="+", help="List(s) to compute the cartesian product of") 
    __parser.add_argument("-u", "--unique", action="store_true", help="Deduplicate lists so that they become sets of unique elements") 
    __parser.add_argument("-U", "--Universally_unique", action="store_true", help="Deduplicate the resulting cartesian product so that the final result is a set of unique elements") 
    return __parser.parse_args() 


def cartesianProduct(__unique, __Universally_unique, *__list): 

    from itertools import product 

    __cartesianProduct = product([]) 

    if __unique: 
     __cartesianProduct = product(sorted(set(__list[0])), sorted(set(__list[len(__list)-1]))) 
    else: 
     __cartesianProduct = product(__list[0], __list[len(__list)-1]) 
    if __Universally_unique: 
     __cartesianProduct = sorted(set(__cartesianProduct)) 
     for __element in __cartesianProduct: 
      if __element[0] == __element[1]: 
      __cartesianProduct.remove(__element) 
    return __cartesianProduct 


def main(): 

    __args = createArgumentParser() 

    for __element in cartesianProduct(__args.unique, __args.Universally_unique, *__args.list): 
     print(__element) 

('a', 'd') 
('a', 'e') 
('a', 'f') 
('b', 'd') 
('b', 'e') 
('b', 'f') 
('c', 'd') 
('c', 'e') 
('c', 'f') 

123部分がデカルト積から欠落しています。どうすれば修正できますか?

+0

最初にあなたのフォーマットを修正してください。 – Sraw

+1

本当にたくさんの '__'変数が本当に必要ですか?それは可読性を失う。 –

+1

私は自分のコーディングスタイルについての反発を期待していました。私は独学で初心者です。しかし、私の場合、アンダースコアはさまざまな方法で読みやすさを助けます(聞こえるほど奇妙です)。私はこのプロジェクトの誰とも協力していないので、より標準的なスタイルの必要性は見当たりませんでした。他の人が迷惑をかけることを心に留めておきます。 –

答えて

0

リストのすべてのアイテムのデカルト積を取得するには、*演算子を使用して引数のアンパックを実行します。これは「スプラット」アンパックと呼ばれることがあります。

from itertools import product 

src = ['abc', '123', 'def'] 
cartesian_product = [''.join(t) for t in product(*src)] 
print(cartesian_product) 

出力

['a1d', 'a1e', 'a1f', 'a2d', 'a2e', 'a2f', 'a3d', 'a3e', 'a3f', 'b1d', 'b1e', 'b1f', 'b2d', 'b2e', 'b2f', 'b3d', 'b3e', 'b3f', 'c1d', 'c1e', 'c1f', 'c2d', 'c2e', 'c2f', 'c3d', 'c3e', 'c3f'] 
+0

ありがとう!私はそれが私が得ていなかった単純な何かになると思った。これはトリックです。 –

関連する問題