3 回答
TA贡献1784条经验 获得超7个赞
对于没有任何内置函数的纯循环方法:
def column_sums(square):
result = [0] * len(square[0])
for row in square:
for i in range(len(result)):
result[i] += row[i]
return result
以下使用zip(*...)换位模式:
def column_sums(square):
result = []
for col in zip(*square):
total = 0
for num in col:
total += num
result.append(total)
return result
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和所有其他内置插件,以下将是最短的:
print(list(map(sum, zip(*square))))
TA贡献1895条经验 获得超7个赞
在这里,您可以使用我想到的最简单的溶胶,而无需使用任何花哨的东西。
def column_sums(square):
"""Returns the sum of the columns"""
result = [0,0,0,0]
for element in square:
for i,item in enumerate(element):
result[i] = result[i] + item
return result
TA贡献1775条经验 获得超11个赞
用这个:
def column_sums(square):
result = dict.fromkeys(len(square), 0)
for i, v in enumerate(zip(*square)):
for x in v:
result[i] += x
return result
square = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
print()
或者sum你实际上可以使用:
square = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
print(column_sums(square))
添加回答
举报