将int转换为python列表[duplicate]

qyuhtwio  于 2023-01-03  发布在  Python
关注(0)|答案(1)|浏览(143)
    • 此问题在此处已有答案**:

How to split an integer into a list of digits?(12个答案)
八年前就关门了。
我如何将一个整型转换成一个数字列表,例如。
a = 1234
我得把它当作
[一、二、三、四]
我试过用
名单(a)
但是显示了错误还有什么我能用的

nmpmafwu

nmpmafwu1#

可以先将a转换为字符串:

  1. In [106]: map(int, str(a)) #in python3, you need list(map(int, str(a)))
  2. Out[106]: [1, 2, 3, 4]

或者使用列表解析代替map

  1. In [108]: [int(digit) for digit in str(a)]
  2. Out[108]: [1, 2, 3, 4]

或手动方法:

  1. In [10]: def bar(num):
  2. ...: res=[]
  3. ...: while num>0:
  4. ...: res.append(num%10)
  5. ...: num//=10
  6. ...: return res[::-1]
  7. In [11]: bar(1234567890)
  8. Out[11]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

所有三种方式在时间上都是相同的:

  1. In [24]: def foo(num):
  2. ...: return list(map(int, str(num)))
  3. In [25]: def bar(num):
  4. ...: res=[]
  5. ...: while num>0:
  6. ...: res.append(num%10) #or try divmod(n, 10) if you like builtins
  7. ...: num//=10
  8. ...: return res[::-1]
  9. In [26]: def lstcomp(num):
  10. ...: return [int(digit) for digit in str(num)]
  11. In [27]: num=1234567890123456789012345678901234567890
  12. In [28]: timeit foo(num)
  13. 100000 loops, best of 3: 13.1 µs per loop
  14. In [29]: timeit bar(num)
  15. 100000 loops, best of 3: 15.7 µs per loop
  16. In [30]: timeit lstcomp(num)
  17. 100000 loops, best of 3: 14.6 µs per loop

编辑:

你也可以生成一个元组来表示"链表",就像@J.F. Sebastian提到的那样:

  1. In [523]: f = lambda n, ll=None: f(n//10, (n%10, ll)) if n else ll
  2. In [524]: f(123)
  3. Out[524]: (1, (2, (3, None)))

其可以在O(n)时间内被转换为普通列表:

  1. In [537]: llst=f(123)
  2. ...: res=[]
  3. ...: while llst:
  4. ...: res.append(llst[0])
  5. ...: llst=llst[1]
  6. ...: print res
  7. [1, 2, 3]
展开查看全部

相关问题