[英]sum each rows in array 2d python
我尝试在 python 中创建二维数组,它接受用户的输入以询问要制作多少个二维数组。 我的程序还对数组 2d 中每一行的值求和,并打印每个数组的最大值。
例子:
输入:
2 - for how much array need to create
2 -> for how much size array(rows default = 3)
1 2 3
4 5 6
3
0 0 0
2 3 4
5 6 7
output:
in array 1 is : 2 (represent row) -> (4+5+6) is greatest than (1+2+3)
in array 2 is : 3 (represent row) -> (5+6+7) is greatest
我的程序堆栈如何求和并打印正确的 output。 并且对于 +:. 的一些不受支持的操作数类型也有一些问题。也许有人想帮我修复它。 这是我的代码
A = int(input("enter how many matrix create: "))
for i in range(A):
B = int(input("enter size : "))
matrix = []
print("enter number: ")
for j in range(B):
a =[]
for k in range(B):
a.append(input())
matrix.append(a)
rows = len(matrix)
cols = len(matrix[0])
total=0
for r in range(0, rows):
rowtotal=0
for s in range(0, cols):
rowtotal=rowtotal+int(matrix[r][s])
print(rowtotal)
total=total+rowtotal
print(total)
我需要你对此的意见。 谢谢。
尝试添加字符串类型和 int 类型或不同类型和不同类型时引发“+ 的操作类型不受支持”错误。 您只能连接相同的类型
在这部分代码中,我确实了解了 rowtotal 和 total 的使用。
for r in range(0, rows):
rowtotal=0
for s in range(0, cols):
rowtotal=rowtotal+int(matrix[r][s])
print(rowtotal)
total=total+rowtotal
这是我根据您的问题编写的示例代码。
# accept the number of martix
a = int(input("Enter how many matrix to create: "))
sizes_of_array = []
largest_rows = []
for i in range(a):
b = int(input("\nEnter size: "))
sizes_of_array.append(b)
List = []
# accept input rows
for j in range(b):
Input = input('Enter {}th row separated with blank: '.format(j+1))
temp = Input.split()
List.append([int(x) for x in temp])
# print the matrix you wrote
print('\nYour matrix: ')
for k in range(b):
for l in range(b):
print(List[k][l],end=' ')
print()
# find the row with largest sum value
largest_sum = max(sum(x) for x in List)
for x in List:
if sum(x) == largest_sum:
largest_rows.append(x)
break
# final results
print('\n')
for i in range(a):
print('In array {}, there is {} rows and {} is the greatest.'.format(i+1,sizes_of_array[i],largest_rows[i]))
它根据行数接受输入; 每次一排。
我在输入后打印了整个矩阵。
随意询问您没有得到的代码部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.