gpt4 book ai didi

python - 创建一个 3 x 4 矩阵并添加列

转载 作者:行者123 更新时间:2023-11-28 17:48:25 30 4
gpt4 key购买 nike

For this lab, you will work with two-dimensional lists in Python. Do the following: Write a function that returns the sum of all the elements in a specified column in a matrix using the following header:

def sumColumn(matrix, columnIndex) 

Write a function that displays the elements in a matrix row by row, where the values in each row are displayed on a separate line (see the output below). Write a test program (i.e., a main function) that reads a 3 X 4 matrix and displays the sum of each column. Here is a sample run:

Enter a 3-by-4 matrix row for row 0: 2.5 3 4 1.5 Enter a 3-by-4 matrix row for row 1: 1.5 4 2 7.5 Enter a 3-by-4 matrix row for row 2: 3.5 1 1 2.5

The matrix is 2.5 3.0 4.0 1.5 1.5 4.0 2.0 7.5 3.5 1.0 1.0 2.5

Sum of elements for column 0 is 7.5 Sum of elements for column 1 is 8.0 Sum of elements for column 2 is 7.0 Sum of elements for column 3 is 11.5

到目前为止,这是我的代码:

def main():
matrix = [[],[],[]]
matrix[0].append(raw_input('Enter a 3-by-4 matrix row for row 0:'))
matrix[1].append(raw_input('Enter a 3-by-4 matrix row for row 1:'))
matrix[2].append(raw_input('Enter a 3-by-4 matrix row for row 2:'))
print 'The matrix is:', '\n', matrix[0], '\n', matrix[1], '\n', matrix[2], '\n',

main()

我需要帮助将列加在一起,我可能错误地创建了矩阵我一直在使用 sum = matrix[0][0][0] + matrix[0][0][2]但它确实将它们相加,它只是将两个数字放在一起。
示例:我想要 1 + 2
预期答案 3
出来 12

有没有办法将列表的两个元素加在一起?

最佳答案

raw_input 返回一个字符串,因此需要将其处理为某种形式的数字。

一个要求输入的简短示例,通过空格将其拆分并使它们成为 float:

text = raw_input('row 1: ')
nums = [float(word) for word in text.split()]

此外,您不希望附加到 matrix = [[],[],[]] - 因为您最终会创建一个 3 维结构。将其更改为 matrix = []... 并在每次有输入行时使用 matrix.append(nums)

您可能还想考虑如果输入了无效的数字,或者如果输入的数字没有达到要求的数量会发生什么……但这是一个不同的问题。

关于python - 创建一个 3 x 4 矩阵并添加列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14392408/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com