본문 바로가기
파이썬

파이썬에서 행렬 열 합계

by º기록 2020. 12. 15.
반응형

열 0의 항목을 잘 합할 수 있습니다. 그러나 행렬의 열 2, 3 또는 4를 더하도록 코드를 어디에서 변경합니까? 나는 쉽게 당황합니다.

def main():
    matrix = []

    for i in range(2):
        s = input("Enter a 4-by-4 matrix row " + str(i) + ": ") 
        items = s.split() # Extracts items from the string
        list = [ eval(x) for x in items ] # Convert items to numbers   
        matrix.append(list)

    print("Sum of the elements in column 0 is", sumColumn(matrix))

def sumColumn(m):
    for column in range(len(m[0])):
        total = 0
        for row in range(len(m)):
            total += m[row][column]
        return total

main()

 

해결 방법

 

지정한 열의 합계를 반환하도록 변경된 코드는 다음과 같습니다.

def sumColumn(m, column):
    total = 0
    for row in range(len(m)):
        total += m[row][column]
    return total

column = 1
print("Sum of the elements in column", column, "is", sumColumn(matrix, column))

 

참조 페이지 https://stackoverflow.com/questions/23145684

 

 

반응형

댓글