You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现过滤命令行指定元素后生成所有非空组合

代码修改方案

核心修改逻辑

  • 获取传入的待组合字符列表后,新增过滤步骤剔除所有值为D的元素,无需关注D在参数中的位置
  • 后续所有组合计算基于过滤后的字符列表执行

完整修改后代码

import sys
import itertools
from itertools import combinations

def main():
    number = int(sys.argv[1])
    # 读取指定数量的待组合入参
    raw_chars = sys.argv[2: 2 + number]
    # 过滤所有D字符,不限制D的位置
    filtered_chars = [char for char in raw_chars if char != 'D']
    # 存储所有组合结果
    all_combinations = []
    for length in range(1, len(filtered_chars) + 1):
        for subset in combinations(filtered_chars, length):
            # 把组合拼接为字符串
            all_combinations.append(''.join(subset))
    # 按要求格式输出所有结果
    print(', '.join(all_combinations))

if __name__ == "__main__":
    main()

验证说明

不管入参是python3 combinations.py 4 A B C D还是python3 combinations.py 4 A D C B,输出结果都是A, B, C, AB, AC, BC, ABC,完全符合需求。如果不需要合并输出所有结果,保留原来的逐行打印逻辑即可,只要把循环遍历的对象替换为filtered_chars就行。

内容的提问来源于stack exchange,提问作者Dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 03:27:01