More elegant way of declaring multiple variables at the same time

后端 未结 10 2022
面向向阳花
面向向阳花 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
    
    0 讨论(0)
  • 2020-11-30 17:50

    When people are suggesting "use a list or tuple or other data structure", what they're saying is that, when you have a lot of different values that you care about, naming them all separately as local variables may not be the best way to do things.

    Instead, you may want to gather them together into a larger data structure that can be stored in a single local variable.

    intuited showed how you might use a dictionary for this, and Chris Lutz showed how to use a tuple for temporary storage before unpacking into separate variables, but another option to consider is to use collections.namedtuple to bundle the values more permanently.

    So you might do something like:

    # Define the attributes of our named tuple
    from collections import namedtuple
    DataHolder = namedtuple("DataHolder", "a b c d e f g")
    
    # Store our data
    data = DataHolder(True, True, True, True, True, False, True)
    
    # Retrieve our data
    print(data)
    print(data.a, data.f)
    

    Real code would hopefully use more meaningful names than "DataHolder" and the letters of the alphabet, of course.

    0 讨论(0)
  • 2020-11-30 17:50

    Sounds like you're approaching your problem the wrong way to me.

    Rewrite your code to use a tuple or write a class to store all of the data.

    0 讨论(0)
  • 2020-11-30 17:53

    Use a list/dictionary or define your own class to encapsulate the stuff you're defining, but if you need all those variables you can do:

    a = b = c = d = e = g = h = i = j = True
    f = False
    
    0 讨论(0)
提交回复
热议问题