More elegant way of declaring multiple variables at the same time

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

    This is an elaboration on @Jeff M's and my comments.

    When you do this:

    a, b = c, d
    

    It works with tuple packing and unpacking. You can separate the packing and unpacking steps:

    _ = c, d
    a, b = _
    

    The first line creates a tuple called _ which has two elements, the first with the value of c and the second with the value of d. The second line unpacks the _ tuple into the variables a and b. This breaks down your one huge line:

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

    Into two smaller lines:

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

    It will give you the exact same result as the first line (including the same exception if you add values or variables to one part but forget to update the other). However, in this specific case, yan's answer is perhaps the best.

    If you have a list of values, you can still unpack them. You just have to convert it to a tuple first. For example, the following will assign a value between 0 and 9 to each of a through j, respectively:

    a, b, c, d, e, f, g, h, i, j = tuple(range(10))
    

    EDIT: Neat trick to assign all of them as true except element 5 (variable f):

    a, b, c, d, e, f, g, h, i, j = tuple(x != 5 for x in range(10))
    

提交回复
热议问题