I'm looking for an elegant way to separate numbers in a single digits
For example 20
to be 2, 0
The way that I found is using a list comprehension: [int(num) for num in str(number)]
Is there another way to do that?
Try this:
num = 20
digits = []
for x in range(0,len(str(num))):
digits.append(int(str(num)[x]))
print(digits)
请尝试以下操作:
digits_list = list(str(num))
a math solution (this only works with positive numbers as is):
import math
def get_digits(n):
if n == 0:
return [0]
digits = []
while n:
digits.append(n % 10)
n = n // 10
return list(reversed(digits))
for n in [0, 1, 10, 235, 5555]:
print(n, get_digits(n))
output
0 [0]
1 [1]
10 [1, 0]
235 [2, 3, 5]
5555 [5, 5, 5, 5]
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.