引数として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
部分がデカルト積から欠落しています。どうすれば修正できますか?
最初にあなたのフォーマットを修正してください。 – Sraw
本当にたくさんの '__'変数が本当に必要ですか?それは可読性を失う。 –
私は自分のコーディングスタイルについての反発を期待していました。私は独学で初心者です。しかし、私の場合、アンダースコアはさまざまな方法で読みやすさを助けます(聞こえるほど奇妙です)。私はこのプロジェクトの誰とも協力していないので、より標準的なスタイルの必要性は見当たりませんでした。他の人が迷惑をかけることを心に留めておきます。 –