简体   繁体   English

使用__str __()在python中漂亮地打印节点的链接列表

[英]Pretty printing a linked list of nodes in python using __str__()

I have a node class in python which is something like this 我在python中有一个节点类,就像这样

class Node:
  def __init__(self, value, next, prev, rand):
    self.value = value
    self.next = next
    self.prev = prev
    self.rand = rand

I create a list out of this by creating nodes and setting the appropriate pointers. 我通过创建节点并设置适当的指针来创建一个列表。 Now, i want to pretty print this list : like [1] --> [2] --> [3] and so on. 现在,我想漂亮地打印此列表:例如[1]-> [2]-> [3],依此类推。 If there is a random pointer along with next it will be [1] --> [2] --> [3,4] -->[4] for example. 如果旁边有一个随机指针,则例如为[1]-> [2]-> [3,4]-> [4]。 here 2 next is 3 and 2 rand is 4 while 3 next is 4. I am trying to do this with the built-in str () method in the node class it self. 这里2 next是3,2 rand是4,而3 next是4。我正在尝试使用自身节点类中的内置str ()方法来做到这一点。 I have it as below as of now 我现在有如下

#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))

This pretty prints it without the random pointer. 这漂亮地打印了没有随机指针。 But I am not able to incorporate the random pointer printing in this. 但是我不能在其中加入随机指针打印。 I tried couple of approaches, but it's messing up the brackets. 我尝试了几种方法,但是搞砸了。 How would i go about this ? 我将如何处理?

Thanks 谢谢

Try factoring the printing of the pointers out, that way it may be clearer: 尝试将指针的打印分解出来,这样可能会更清晰:

#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 + ']'

One way to do it is using array slices on the string and injecting the random value into the next node string like this 一种方法是在字符串上使用数组切片,然后将随机值注入到下一个节点字符串中,如下所示

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM