Python:从方程结果创建嵌套列表

标签 python list nested-loops

我对 Python 编程非常陌生,我正在尝试让我的二次方程求解器将 x1 和 x2 的答案“收集”到嵌套列表中。

它很好地求解了方程并得到了正确的结果,并且我能够按照我想要的方式得到结果,但我无法在循环结束时将它们收集到同一个列表中。代码如下:

from math import sqrt

abcList = [[1, 2, 1], [9, 12, 4], [1, -7, 0], [1, -2, -3]]

for abc in abcList:
    a, b, c = abc
    q = b**2 - 4*a*c

    if q > 0:
        q_sqrt = sqrt(q)
        x1 = (-b + q_sqrt)/(2*a)
        x2 = (-b - q_sqrt)/(2*a)

    elif q == 0:
        x1 = -b/(2*a)
        x2 = x1

    else:
        raise ValueError("q is negative.")

    resultList = []

    print ('x1 = ', x1)

    resultList.append(x1)

    print ('x2 = ', x2)

    resultList.append(x2)

    #print ('a = ', a, ', b = ', b, 'and c = ',c)

    print (resultList)

print ('-----')

这是我得到的结果:

x1 =  -1.0
x2 =  -1.0
[-1.0, -1.0]
x1 =  -0.6666666666666666
x2 =  -0.6666666666666666
[-0.6666666666666666, -0.6666666666666666]
x1 =  7.0
x2 =  0.0
[7.0, 0.0]
x1 =  3.0
x2 =  -1.0
[3.0, -1.0]
-----

这就是我想要的结果:

x1 =  -1.0
x2 =  -1.0

x1 =  -0.6666666666666666
x2 =  -0.6666666666666666

x1 =  7.0
x2 =  0.0

x1 =  3.0
x2 =  -1.0


[[-1.0, -1.0], [-0.6666666666666666, -0.6666666666666666], [7.0, 0.0], [3.0, -1.0]]
-----

最佳答案

您只需要稍微重新组织一下您的代码即可。在 for 循环外部初始化 resultList,并将每对答案附加为 2 元素列表。

    from math import sqrt

    abcList = [[1, 2, 1], [9, 12, 4], [1, -7, 0], [1, -2, -3]]
    resultList = []

    for abc in abcList:
        a, b, c = abc
        q = b**2 - 4*a*c

        if q > 0:
            q_sqrt = sqrt(q)
            x1 = (-b + q_sqrt)/(2*a)
            x2 = (-b - q_sqrt)/(2*a)
        elif q == 0:
            x1 = -b/(2*a)
            x2 = x1
        else:
            raise ValueError("q is negative.")

        #print ('a = ', a, ', b = ', b, 'and c = ',c)
        print ('x1 = ', x1)
        print ('x2 = ', x2)
        resultList.append([x1, x2])

    print (resultList)        
    print ('-----')    

输出

x1 =  -1.0
x2 =  -1.0
x1 =  -0.666666666667
x2 =  -0.666666666667
x1 =  7.0
x2 =  0.0
x1 =  3.0
x2 =  -1.0
[[-1.0, -1.0], [-0.66666666666666663, -0.66666666666666663], [7.0, 0.0], [3.0, -1.0]]
-----

顺便说一句,不需要仅仅为了求平方根而导入 math 模块:您可以使用 ** 求幂运算符,这比创建函数更有效打电话。

q_sqrt = q ** 0.5

关于Python:从方程结果创建嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35359802/

相关文章:

python - 显示目录中的所有图像时出错

python - uWSGI 日志轮换不工作

python - 子进程无法捕获标准输出

r - 减去R中向量列表中类似命名的元素

python - QListView 中自定义 IndexWidget 的平滑延迟加载和卸载

c# - List inside list 不打印元素,而是显示 System.Collections.Generic.List`1[System.Object]

python - : compound conditional expressions AND'd [python] 中的 while 循环条件

algorithm - 嵌套 for 循环的运行时复杂度

c++ - 调试嵌套 for 循环的正常方法是什么?

cuda - 我们什么时候需要在 CUDA 中使用二维线程?