More elegant way of declaring multiple variables at the same time

后端 未结 10 2116
面向向阳花
面向向阳花 2020-11-30 17:12

To declare multiple variables at the \"same time\" I would do:

a, b = True, False

But if I had to declare much more variables, it turns les

10条回答
  •  生来不讨喜
    2020-11-30 17:44

    I like the top voted answer; however, it has problems with list as shown.

      >> a, b = ([0]*5,)*2
      >> print b
      [0, 0, 0, 0, 0]
      >> a[0] = 1
      >> print b
      [1, 0, 0, 0, 0]
    

    This is discussed in great details (here), but the gist is that a and b are the same object with a is b returning True (same for id(a) == id(b)). Therefore if you change an index, you are changing the index of both a and b, since they are linked. To solve this you can do (source)

    >> a, b = ([0]*5 for i in range(2))
    >> print b
    [0, 0, 0, 0, 0]
    >> a[0] = 1
    >> print b
    [0, 0, 0, 0, 0]
    

    This can then be used as a variant of the top answer, which has the "desired" intuitive results

    >> a, b, c, d, e, g, h, i = (True for i in range(9))
    >> f = (False for i in range(1)) #to be pedantic
    

提交回复
热议问题