简体   繁体   中英

How can I add a list of intergers together using a comprehension?

I'm trying to convert a number to a string, then to a list, then converting the list of numbers into integers, then adding these numbers together.

Here's an example:

Number = 123456789
SplitList = (list(str(Number)))
IntergerList = list(int(I) for I in SplitList)
A = 0
A = (A + S for S in IntergerList)

Why doesn't this work?

Why reinvent the wheel? Just use the built-in sum function:

sum(integerList)

Why transform it to a list? This is a math problem, do the maths :), it's another option just only another:

Number = 123456789
res = 0
while Number:
  res += Number % 10
  Number //= 10

res = 45

Or with divmod like:

Number = 3332
res = 0
while(Number != 0):
  parts = divmod(Number, 10)
  res += parts[1]
  Number = parts[0]

print(res)

You can do it by passing a generator expression to the builtin function sum .

number = 123456789
sum(int(digit) for digit in str(number))

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