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

标签 python

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/

相关文章:

python - 如何使用 C++ 正确使用 tensorflow 从 YOLO 模型获取输出?

python - django post_migrate 信号问题

javascript - Django Rest 框架正在从数据库中返回 'u 前缀到 Angular

python - Tensorflow 抛出 "TypeError: unhashable type: ' list'"错误

python - django.db.utils.IntegrityError : (1062, "Duplicate entry ' ' 对于键 'slug' ")

python - Django - 用户在注销后通过单击浏览器后退按钮重新进入 session

python - PyTorch - 在 torch.sort 之后取回原始张量顺序的更好方法

python - 训练 '\x00' s 和 TypeError : stat() argument 1 must be encoded string without null bytes, 不是 str

Python 3 替换行

python - 在 python 中解析大文本的最快方法