[英]Pretty printing a linked list of nodes in python using __str__()
我在python中有一个节点类,就像这样
class Node:
def __init__(self, value, next, prev, rand):
self.value = value
self.next = next
self.prev = prev
self.rand = rand
我通过创建节点并设置适当的指针来创建一个列表。 现在,我想漂亮地打印此列表:例如[1]-> [2]-> [3],依此类推。 如果旁边有一个随机指针,则例如为[1]-> [2]-> [3,4]-> [4]。 这里2 next是3,2 rand是4,而3 next是4。我正在尝试使用自身节点类中的内置str ()方法来做到这一点。 我现在有如下
#pretty print a node
def __str__(self):
if self.next is None:
return '[%d]' % (self.value)
else:
return '[%d]-->%s' % (self.value, str(self.next))
这漂亮地打印了没有随机指针。 但是我不能在其中加入随机指针打印。 我尝试了几种方法,但是搞砸了。 我将如何处理?
谢谢
尝试将指针的打印分解出来,这样可能会更清晰:
#pretty print a node
def __str__(self):
if self.next is None:
return self.stringify_pointers()
else:
return '%s-->%s' % (self.stringify_pointers(), str(self.next))
def stringify_pointers(self):
s = '['
if self.next:
s += str(self.next) + (',' if self.rand else '')
if self.rand:
# <> to distinguish rand from next
s += '<%s>' % str(self.rand)
return s + ']'
一种方法是在字符串上使用数组切片,然后将随机值注入到下一个节点字符串中,如下所示
def __str__(self):
if self.next is None:
return '[%d]' % (self.value)
else:
nn = str(self.next)
if self.rand != None:
nn = '%s,%d%s' % (nn[:2], self.rand, nn[2:])
return '[%d]-->%s' % (self.value, nn)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.