所以我在这里有这个功能:
def row_sums(square):
"""Returns a list of the row sums in a magic square"""
numbers = []
for row in square:
result = 0
for col in row:
result += col
numbers.append(result)
return numbers
当输入如下的魔方时,它将返回行的总和,而不使用内置函数" sum":
square = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
print(row_sums(square))
所以这将返回:
[10, 26, 42, 58]
所以这个好,但是对于我实验室测验中的下一个问题。它要求我修改函数,以便它将打印列的总和。例如,输入相同的内容:
square = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
print(column_sums(square))
将返回
[28, 32, 36, 40]
无法搞清楚这一点。如果有人有时间帮助我,那将会很棒! (注意:该函数的目的不是使用" sum"这是不常见的函数,但它适用于嵌套循环实践) 干杯
答案 0 :(得分:0)
您可以使用它来执行所需的OP ..
sum_of_columns = [sum([row[i] for row in square]) for i in range(0,len(square[0]))]
没有内置和函数:
def array_sum(a):
result=0
for i in a:
result+=i
return result
sum_of_columns = [array_sum([row[i] for row in square]) for i in range(0,len(square[0]))]
根据OP条件函数做column_sum:
def column_sums(square):
"""Returns a list of the columns sums in a magic square"""
numbers = []
for i in range(0, len(square[0])):
result = 0
for row in square:
result += row[i]
numbers.append(result)
return numbers