我被要求将一个数字转换成它的数字的链接列表: ex:head = number_to_list(120) number_to_list是我应该写的函数,它应该返回它的数字列表listutils.from_linked_list(head) == [1,2,0],而不用像list和dicts.I这样的数据结构。我试着这样写:
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帮助我完成这个任务。
发布于 2014-02-02 16:43:56
您可以通过将数字转换为字符串并使用列表理解来完成此操作。
In [1]: foo = 12345
In [2]: [int(digit) for digit in str(foo)]
Out[2]: [1, 2, 3, 4, 5]或者更短的版本建议:
map(int, list(str(foo)))但似乎您使用的是自定义列表类。键仍然是将数字转换为字符串。
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发布于 2014-02-02 16:46:38
您可以将数字转换为字符串并遍历每个字符,在需要时将它们转换回数字。
例:
def number_to_list(number):
head,tail = None,None
for x in str(number):
#do stuff发布于 2014-02-02 16:55:19
>>> 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]https://stackoverflow.com/questions/21513156
复制相似问题