简体   繁体   中英

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:

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

it returned "bad operand type for abs(): 'list'"

so I tried using map like:

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:

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). Hence

tmp = sum(map(abs, board))

You can do this with a generator expression passed to sum() :

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

You can read more about generator expressions in the original PEP .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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