将单个数字转换为单个数字 Python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21270320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:26:43  来源:igfitidea点击:

Turn a single number into single digits Python

pythonlistnumbers

提问by user3221242

I want to make a number , for example 43365644 into single numbers [4,3,3....,4,4]

我想把一个数字,例如 43365644 变成单个数字 [4,3,3....,4,4]

and append it on a list

并将其附加到列表中

回答by user3221242

This can be done quite easily if you:

如果您:

  1. Use strto convert the number into a string so that you can iterate over it.

  2. Use a list comprehensionto split the string into individual digits.

  3. Use intto convert the digits back into integers.

  1. 使用str将数字转换成字符串,这样就可以在它迭代。

  2. 使用列表理解将字符串拆分为单个数字。

  3. 使用int到数字转换回整数。

Below is a demonstration:

下面是一个演示:

>>> n = 43365644
>>> [int(d) for d in str(n)]
[4, 3, 3, 6, 5, 6, 4, 4]
>>>

回答by Slater Victoroff

If you want to change your number into a list of those numbers, I would first cast it to a string, then casting it to a list will naturally break on each character:

如果您想将您的数字更改为这些数字的列表,我会先将其转换为 a string,然后将其转换为列表自然会在每个字符上中断:

[int(x) for x in str(n)]

回答by Maxime Lorant

The easiest way is to turn the int into a string and take each character of the string as an element of your list:

最简单的方法是将 int 转换为字符串并将字符串的每个字符作为列表的元素:

>>> n = 43365644 
>>> digits = [int(x) for x in str(n)]
>>> digits
[4, 3, 3, 6, 5, 6, 4, 4]
>>> lst.extend(digits)  # use the extends method if you want to add the list to another

It involves a casting operation, but it's readable and acceptable if you don't need extreme performance.

它涉及强制转换操作,但如果您不需要极端性能,它是可读且可接受的。

回答by inspectorG4dget

Here's a way to do it without turning it into a string first (based on some rudimentary benchmarking, this is about twice as fast as stringifying nfirst):

这是一种无需先将其转换为字符串的方法(基于一些基本的基准测试,这大约是n先字符串化的两倍):

>>> n = 43365644
>>> [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10))-1, -1, -1)]
[4, 3, 3, 6, 5, 6, 4, 4]