我被要求将一个数字转换为其数字的链接列表:
例如:head = number_to_list(120)
number_to_list是我应该编写的函数,它应该返回一个数字列表listutils.from_linked_list(head) == [1,2,0]
而不使用像list和dicts这样的数据结构。我试着这样写:
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循环中我应该以这样的方式编写代码,使其转到数字的第一个数字并创建它的节点。我在这里被阻止。请帮助我。
答案 0 :(得分:4)
您可以通过将数字转换为字符串并使用列表理解来完成此操作。
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
答案 1 :(得分:2)
您可以将数字转换为字符串并遍历每个字符,并在需要时将它们转换回数字。
例如:
def number_to_list(number):
head,tail = None,None
for x in str(number):
#do stuff
答案 2 :(得分:2)
>>> 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]
答案 3 :(得分:1)
我认为如果像这样的代码你的问题将会解决:
def number_to_list(number):
head,tail = None,None
for x in str(number):
node = Node(int(x))
if head:
tail.next = node
else:
head = node
tail = node
second = head.next
third = second.next
fourth = third.next
答案 4 :(得分:0)
下面:
[int(i) for i in str(num)]