首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将数字转换为python中数字的链接列表

如何将数字转换为python中数字的链接列表
EN

Stack Overflow用户
提问于 2014-02-02 16:40:39
回答 4查看 5K关注 0票数 3

我被要求将一个数字转换成它的数字的链接列表: ex:head = number_to_list(120) number_to_list是我应该写的函数,它应该返回它的数字列表listutils.from_linked_list(head) == [1,2,0],而不用像list和dicts.I这样的数据结构。我试着这样写:

代码语言:javascript
运行
复制
def number_to_list(number):        
    head,tail = None,None
    for x in number:
        node = Node(x)
        if head:
           tail.next = node
        else:
           head = node
           tail = node
    second = head.next
    third = second.next
    fourth = third.next

但是我知道我完全错了,因为在for循环中,我应该用这样的方式来编写代码,它会到达数字的第一个数字,并创建一个节点。我被阻塞了,here.Please帮助我完成这个任务。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2014-02-02 16:43:56

您可以通过将数字转换为字符串并使用列表理解来完成此操作。

代码语言:javascript
运行
复制
In [1]: foo = 12345

In [2]: [int(digit) for digit in str(foo)]
Out[2]: [1, 2, 3, 4, 5]

或者更短的版本建议:

代码语言:javascript
运行
复制
map(int, list(str(foo)))

但似乎您使用的是自定义列表类。键仍然是将数字转换为字符串。

代码语言:javascript
运行
复制
def number_to_list(number):        
    head = tail = None        #you can chain assignments if they have the same value
    for x in str(number):
        if not x.isdigit():
            continue # skip leading `-`
        node = Node(x)
        if head is not None:  #more pythonic than `if head`
           tail.next = node
        else:
           head = node
           tail = node
    return head    # don't forget your return code
票数 5
EN

Stack Overflow用户

发布于 2014-02-02 16:46:38

您可以将数字转换为字符串并遍历每个字符,在需要时将它们转换回数字。

例:

代码语言:javascript
运行
复制
def number_to_list(number):        
    head,tail = None,None
    for x in str(number):
        #do stuff
票数 2
EN

Stack Overflow用户

发布于 2014-02-02 16:55:19

代码语言:javascript
运行
复制
>>> def foobar(a):
>>>     if len(a) > 1:
>>>        return a[0]+','+foobar(a[1:])
>>>     else:
>>>        return a[0]
>>> 
>>> map(int,foobar(str(120)).split(','))
>>> [1, 2, 0]
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21513156

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档