我想编写一段代码来计算列表每行中元素的总和,并返回行总和的新列表。例如
def row_sums(square):
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]
的输出。当第一行的总和等于10时,第二行的总和等于26,依此类推。但是我不想使用内置的sum函数来做到这一点。我该怎么做呢?提前致谢。
答案 0 :(得分:2)
一段简单的代码,用于计算列表每行中元素的总和。
square = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
su=[sum(i) for i in square]
print (su)
输出:
[10, 26, 42, 58]
答案 1 :(得分:1)
如果你真的不能使用sum()
函数,这里有一个对行进行求和的函数,我已经明确地写了它来显示步骤但是一旦你理解了什么就值得查看列表推导正在进行:
def row_sums(square):
# list to store sums
output = []
# go through each row in square
for row in square:
# variable to store row total
total = 0
# go through each item in row and add to total
for item in row:
total += item
# append the row's total to the output list
output.append(total)
# return the output list
return output
然后可以这样使用:
square = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
row_totals = row_sums(square)
编辑:
在回答你的评论时,我会做这样的事情:
def sum_columns(square):
# as before have a list to store the totals
output = []
# assuming your square will have the same row length for each row
# get the number of columns
num_of_columns = len(square[0])
# iterate over the columns
for i in xrange(0, num_of_columns):
# store the total for the column (same as before)
total = 0
# for each row, get the value for the column and add to the column total
# (value at index i)
for row in square:
total += row[i]
# append the total to the output list
output.append(total)
# return the list of totals
return output
答案 2 :(得分:1)
在某一点上你必须使用sum函数(作为sum()或“+”),但你可以使用像
这样的地图list(map(sum, square))
答案 3 :(得分:1)
模块functools
有一个有用的reduce function
,您可以用它来编写自己的和函数。如果您对lambda functions
感到满意,可以这样做:
lst = [0,1,2,3,4,5]
将sum(lst)
作为15
。但是,您自己与reduce
的求和函数可能类似于:
from functools import reduce
reduce(lambda x,y: x + y, l)
哪个woudld也给15
。您应该能够自己编写其余部分(即在另一个列中处理行的列表中)。
答案 4 :(得分:1)
您也可以使用comprehension和reduce执行此操作:
SELECT s.price,
l.rebate,
rebatec AS valrebate,
priceworebate AS worebate,
priceworebate/100*s.tax AS valtax,
priceworebate+priceworebate/100*s.tax AS finalprice
FROM tlist l, tcontent s, LATERAL
(SELECT s.price/100*l.rebate AS rebatec,
s.price-s.price/100* l.rebate AS priceworebate
)sub
WHERE l.billno=s.billno;
答案 5 :(得分:1)
您可以将这些行添加到现有功能中:
inetnum: 90.255.32.0 - 90.255.63.255
netname: VODAFONE-DYN-IP
descr: Dynamic IP Addresses
descr: Vodafone Consumer Broadband