【问题标题】:Python 3 Adding Diagonals in an ArrayPython 3 在数组中添加对角线
【发布时间】:2016-03-30 15:45:23
【问题描述】:

我似乎找不到任何关于在 4x4 数组中添加两条对角线的方法。

row = 4
column = 4
lis1 = [23.5, 30.1, 56.2, 11.9]
lis2 = [45.1, 8.9, 77.3, 54.1]
lis3 = [6.6, 7.7, 8.8, 2.2]
lis4 = [9.9, 8.9, 7.8, 23.6]
array = [lis1, lis2, lis3, lis4]

def diagonalSum(array):
    count = 0
    for i in range (len(array)):
        count += array[i][i]
    print ('The total of the elements in both diagonals equals  %.2f' %(count))
    return count

当我调用该函数时,它会打印 lis1[0]+lis2[1]+lis3[2]+lis4[3] 的总数,但我还需要它来计算 lis4[0]+lis3[1]+lis2[2]+lis1[3] 的总数并显示两条对角线的总数。有什么建议吗?

【问题讨论】:

    标签: arrays list function python-3.x diagonal


    【解决方案1】:

    您只计算从左上角到右下角的对角线,在本例中为 0,0 1,1 2,2 3,3。您还需要从右上角到左下角计算另一条对角线,即 0,3 1,2 2,1 3,0

    要使用一个循环,您可以添加另一个您自己递增或递减的索引,像这样

    j = len(array) - 1
    for i in range(len(array)):
        # diagonal from top left to bottom right
        count += array[i][i]
        # diagonal from bottom left to top right
        count += array[j][i]
        j -= 1
    

    【讨论】:

    • 我知道这一定是显而易见的......大脑只是被炸了。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    • 2017-05-06
    相关资源
    最近更新 更多