【问题标题】:Removing one name from command line and taking the combinations of the rest从命令行中删除一个名称并取其余名称的组合
【发布时间】:2022-01-01 15:29:02
【问题描述】:

我想使用 python3 combinations.py 4 A B C D 运行我的 python 代码

其中 4 是我想查看的字符数,A、B、C 和 D 是这 4 个字符。但挑战是我总是想从该组合的输出中省略 D。所以上述情况的输出将是:A, B, C, AB, AC, BC, ABC

这就是我正在尝试的。但这只有在最后一个命令行参数是 D 时才有效。如果 D 介于两者之间或在第一个参数的右边,那么它将不起作用。

import sys
import itertools
from itertools import combinations
def main():
    number = int(sys.argv[1])
    a_list = sys.argv[2:number+1]
    print("So all possible combinations except D:\n")
    for L in range(1, len(a_list)+1):
        for subset in itertools.combinations(a_list, L):
            print(*list(subset), sep=',')

再举一个例子:如果我给出python3 combinations.py 4 A D C B,那么我的代码将给出:A, D, C, AD, AC, DC, ADC,但我需要输出:A, B, C, AB, AC, BC, ABC

我该怎么做。请帮帮我。

【问题讨论】:

    标签: python python-3.x combinations command-line-arguments


    【解决方案1】:

    好的,我正试图找到一种方法,这就是我刚才所做的,它工作正常。

    import sys
    import itertools
    from itertools import combinations
    def main():
        number = int(sys.argv[1])
        a_list = sys.argv[2:number+2]
        print(a_list)
        print(len(a_list))
        if 'D' in a_list: a_list.remove('D')
        print(a_list)
        print(len(a_list))
        print("So all possible combinations except D:\n")
        for L in range(1, len(a_list)+1):
            for subset in itertools.combinations(a_list, L):
                print(*list(subset), sep=',')
                
                
    if __name__ == '__main__':
        main()
    

    【讨论】:

      猜你喜欢
      • 2019-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-21
      • 1970-01-01
      • 2014-04-11
      • 2020-07-11
      相关资源
      最近更新 更多