Confusing […] List in Python: What is it?

前端 未结 9 2129
傲寒
傲寒 2020-11-29 10:52

So I was writing up a simple binary tree in Python and came across [...]

I don\'t believe this to be related to the Ellipsis object, more it seems to have something

9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 11:48

    Ok, so in points:

    1. You're creating infinite data structure:

      def Keys(x,y=[])
      will use the same 'y' in each call. This just isn't correct.

    2. The print statement, however, is clever enough not to print an infinite data, but to mark self-reference with a [...] (known as Ellipsis)

    3. The Python will allow you to address such structure correctly, so you can write
      a.keys()[1][1][1]
      and so on. Why shouldn't you?
    4. The y = y[:] statement simply copies the list y. Can be done more soundly with y = list(y)

    Try using the following code:

    def Keys(x,y=None):
        if y is None:
            y = []
        if len(x):
            y += [x[2], Keys(x[0],y), Keys(x[1],y)]
        return y
    

    But still I guess that it can bite you. You're still using the same variable y (I mean the same object) in three places in one expression:

     y += [x[2], Keys(x[0], y), Keys(x[1], y)] 

    Is that what you really want to achieve? Or maybe you should try:

    def mKeys(x,y=None):
        if y is None:
            y = []
        if len(x):
           z = [x[2], mKeys(x[0], y), mKeys(x[1],y)]
           return z
       return []
    

提交回复
热议问题