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

如何在Python中移除结果里a=0且b=0的条目

修改代码移除a=0, b=0的结果

有两种简单的修改方式,同时还可以优化你的计算函数让代码更高效:

方法1:修改判断条件,直接排除目标组合

在原有的判断条件里,加上对a=0且b=0的排除逻辑,修改后的代码如下:

def determinate(a,b):
    return a * (3*2 - 0*2) - 0 * (4*2 - b*2) + b * (4*0 - 3*b)

for a in range(-100,101):
    for b in range(-100,101):
        if determinate(a,b) == 0 and not (a == 0 and b == 0):
            print(f"a: {a}, b: {b}")

方法2:在循环中提前跳过该组合

如果遇到a和b同时为0的情况,直接跳过当前循环,不进行后续判断:

def determinate(a,b):
    return a * (3*2 - 0*2) - 0 * (4*2 - b*2) + b * (4*0 - 3*b)

for a in range(-100,101):
    for b in range(-100,101):
        if a == 0 and b == 0:
            continue
        if determinate(a,b) == 0:
            print(f"a: {a}, b: {b}")

额外优化:简化计算函数

你的determinate函数可以化简,原计算式展开后等价于6*a - 3*b²,简化后函数更高效,修改后代码如下(以方法1为例):

def determinate(a,b):
    return 6*a - 3*(b**2)

for a in range(-100,101):
    for b in range(-100,101):
        if determinate(a,b) == 0 and not (a == 0 and b == 0):
            print(f"a: {a}, b: {b}")

修改后运行,输出结果就会去掉a: 0, b: 0,剩下的条目和你之前得到的一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 23:17:31