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

如何用Python列表推导式生成运算符全组合的二维测试用例列表?

生成包含'+', '-', '*', '/'的非递增4元组组合列表

你想要的是所有非递增顺序(按'+', '-', '/', '*'的优先级)的4元运算符组合,示例输出如下:

[('+', '+', '+', '+'),
 ('+', '+', '+', '-'),
 ('+', '+', '+', '/'),
 ('+', '+', '+', '*'),
 ('+', '+', '-', '-'),
 ('+', '+', '-', '/'),
 ('+', '+', '-', '*'),
 ('+', '+', '/', '/'),
 ('+', '+', '/', '*'),
 ('+', '+', '*', '*'),
 ('+', '-', '-', '-'),
 ('+', '-', '-', '/'),
 ('+', '-', '-', '*'),
 ('+', '-', '/', '/'),
 ('+', '-', '/', '*'),
 ('+', '-', '*', '*'),
 ('+', '/', '/', '/'),
 ('+', '/', '/', '*'),
 ('+', '/', '*', '*'),
 ('+', '*', '*', '*'),
 ('-', '-', '-', '-'),
 ('-', '-', '-', '/'),
 ('-', '-', '-', '*'),
 ('-', '-', '/', '/'),
 ('-', '-', '/', '*'),
 ('-', '-', '*', '*'),
 ('-', '/', '/', '/'),
 ('-', '/', '/', '*'),
 ('-', '/', '*', '*'),
 ('-', '*', '*', '*'),
 ('/', '/', '/', '/'),
 ('/', '/', '/', '*'),
 ('/', '/', '*', '*'),
 ('/', '*', '*', '*'),
 ('*', '*', '*', '*')]

你之前用的[[x] * 4 for x in ('+','-','*', '/')]只能生成4个单一符号重复4次的列表(比如['+','+','+','+']),无法生成所有组合,下面是两种正确实现方式:

方法1:使用itertools.combinations_with_replacement(推荐)

Python标准库的itertools.combinations_with_replacement专门用于生成允许重复元素的组合,且组合元素会保持输入的顺序(非递增,匹配你的示例规则):

import itertools

operators = ('+', '-', '/', '*')
test_cases = list(itertools.combinations_with_replacement(operators, 4))

运行这段代码后,test_cases就是你需要的列表。

方法2:手动嵌套循环实现

如果不想依赖标准库,可以通过嵌套循环控制每个位置的运算符索引不小于前一个,来生成符合要求的组合:

operators = ('+', '-', '/', '*')
test_cases = []

# 每个循环的起始索引不小于前一个,保证非递增顺序
for i in range(len(operators)):
    for j in range(i, len(operators)):
        for k in range(j, len(operators)):
            for l in range(k, len(operators)):
                test_cases.append((operators[i], operators[j], operators[k], operators[l]))

这两种方法生成的结果完全匹配你的示例需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 06:10:33