使用python将数字分成数字并将它们保存在列表(数组)中
我想将数字分成数字并将它们保存在 python 的列表(或数组)中。 创建列表
dig = [0 for i in range(10)]
所以首先我应该像然后一样
i = 0
while num > 9:
dig[i] = num % 10
i += 1
num /= 10
dig[i] = num
但是我真的不喜欢只创建10个空格的列表,是否可以在不重复循环的情况下获得数字的长度
i = 0
num2 = num
while num2 > 9:
num2 /= 10
i += 1
i += 1
,然后重复代码的第一部分?还是按照我一开始做的那样做?我不知道数字的确切长度,但不会很长
所以有什么建议吗?也许您知道将数字分成数字的更好方法,或者也许还有其他方法。
I want to divide number into digits and save them in list (or array) in python. So firstly I should create list like
dig = [0 for i in range(10)]
and then
i = 0
while num > 9:
dig[i] = num % 10
i += 1
num /= 10
dig[i] = num
But I don't really like just creating list for 10 spaces, is it possible to get length of number without repeating loop
i = 0
num2 = num
while num2 > 9:
num2 /= 10
i += 1
i += 1
and then repeat first part of code? Or just make as I made in first place? I don't know exact length of number but it won't be very long
So any advices? Maybe you know better way to divide numbers into digits, or maybe something else.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于您只是按从小到大的顺序添加数字,因此只需使用一个空列表:
或者,只需执行
Which 即可将 ie
123
转换为'123'
,然后将将每个数字放回一个数字并将它们放入一个列表中,得到[1, 2, 3]
。如果您希望它的顺序与您的版本相同,请使用
如果您真的只想获取数字的长度,最简单的做法是
len(str(num))
将其转换为字符串然后得到长度。Since you're just adding the digits from smallest to greatest in order, just use an empty list:
Alternatively, just do
Which will turn i.e.
123
into'123'
then turn each digit back into a number and put them into a list, resulting in[1, 2, 3]
.If you want it in the same order as your version, use
If you really just want to get the length of a number, it's easiest to do
len(str(num))
which turns it into a string then gets the length.假设
num
是正整数,则位数等于int(math.log10(num) + 1)
。但比这更好的是只使用
list
的append
方法——这样您就不必事先知道长度。甚至更容易(尽管列表将以相反的顺序排列):
或
Assuming
num
is a positive integer, the number of digits is equal toint(math.log10(num) + 1)
.But better than that is to just use the
append
method oflist
-- then you won't have to know the length beforehand.Even easier (though the list will be in reverse order):
or
虽然
map
通常被认为是非Pythonic,但这个任务绝对适合它:Although
map
is often said to be unpythonic, this task is definitely for it: