简体   繁体   English

如何计算列表中整数的绝对值之和?

[英]How to calculate the sum of the absolute value of integers in a list?

I tried to calc the sum of the abs value of nums in a list like this:我试图在这样的列表中计算 nums 的 abs 值的总和:

stage = sum(sum(abs(board))) # board is a list named before

it returned "bad operand type for abs(): 'list'"它返回“abs()的错误操作数类型:'list'”

so I tried using map like:所以我尝试使用 map 像:

tmp = list(map(abs,board))

however, the error information remains the same.但是,错误信息保持不变。 What can I do?我能做些什么?

The statements using the sum of 'board' are shown as following:使用'board'之和的语句如下所示:

stage = sum(sum(board))
colfull = numpy.zeros((8, 8), dtype=numpy.int64)
colfull[:,numpy.sum(map(abs,board), axis = 0) == 8] = True

You need map (to map the abs ) and sum (to sum the values).您需要map (到 map 的abs )和sum (对值求和)。 Hence因此

tmp = sum(map(abs, board))

You can do this with a generator expression passed to sum() :您可以使用传递给sum()的生成器表达式来执行此操作:

stage = sum(abs(x) for x in board)

You can read more about generator expressions in the original PEP .您可以在原始PEP中阅读有关生成器表达式的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM