More elegant way of declaring multiple variables at the same time

后端 未结 10 2123
面向向阳花
面向向阳花 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:33

    What's the problem , in fact ?

    If you really need or want 10 a, b, c, d, e, f, g, h, i, j , there will be no other possibility, at a time or another, to write a and write b and write c.....

    If the values are all different, you will be obliged to write for exemple

    a = 12
    b= 'sun'
    c = A() #(where A is a class)
    d = range(1,102,5)
    e = (line in filehandler if line.rstrip())
    f = 0,12358
    g = True
    h = random.choice
    i = re.compile('^(!=  ab).+?')
    j = [78,89,90,0]
    

    that is to say defining the "variables" individually.

    Or , using another writing, no need to use _ :

    a,b,c,d,e,f,g,h,i,j =\
    12,'sun',A(),range(1,102,5),\
    (line for line in filehandler if line.rstrip()),\
    0.12358,True,random.choice,\
    re.compile('^(!=  ab).+?'),[78,89,90,0]
    

    or

    a,b,c,d,e,f,g,h,i,j =\
    (12,'sun',A(),range(1,102,5),
     (line for line in filehandler if line.rstrip()),
     0.12358,True,random.choice,
     re.compile('^(!=  ab).+?'),[78,89,90,0])
    

    .

    If some of them must have the same value, is the problem that it's too long to write

    a, b, c, d, e, f, g, h, i, j = True, True, True, True, True, False, True ,True , True, True 
    

    ?

    Then you can write:

    a=b=c=d=e=g=h=i=k=j=True
    f = False
    

    .

    I don't understand what is exactly your problem. If you want to write a code, you're obliged to use the characters required by the writing of the instructions and definitions. What else ?

    I wonder if your question isn't the sign that you misunderstand something.

    When one writes a = 10 , one don't create a variable in the sense of "chunk of memory whose value can change". This instruction:

    • either triggers the creation of an object of type integer and value 10 and the binding of a name 'a' with this object in the current namespace

    • or re-assign the name 'a' in the namespace to the object 10 (because 'a' was precedently binded to another object)

    I say that because I don't see the utility to define 10 identifiers a,b,c... pointing to False or True. If these values don't change during the execution, why 10 identifiers ? And if they change, why defining the identifiers first ?, they will be created when needed if not priorly defined

    Your question appears weird to me

提交回复
热议问题