3 回答

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超7個(gè)贊
對(duì)于沒(méi)有任何內(nèi)置函數(shù)的純循環(huán)方法:
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]
請(qǐng)注意,您通過(guò)壓縮行來(lái)獲取列。如果您可以使用sum和所有其他內(nèi)置插件,以下將是最短的:
print(list(map(sum, zip(*square))))

TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超7個(gè)贊
在這里,您可以使用我想到的最簡(jiǎn)單的溶膠,而無(wú)需使用任何花哨的東西。
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貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超11個(gè)贊
用這個(gè):
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你實(shí)際上可以使用:
square = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
print(column_sums(square))
添加回答
舉報(bào)