Easiest way to initialize a large number of variables
-
29-05-2021 - |
質問
Assume you are given a large number of variables that need to be initialized to None. A naive way to do this would be to count the number of variables on the left, and create a list of the same size on the right:
a, b, c, d, e, f, g, h, i, j = [None]*10
Is there a way to do this without having to count the variables? If one uses this pattern often, it could become tedious to have to count the number of variables.
解決
a = b = c = d = e = f = g = h = i = j = None
Note: don't use this for mutable types. If you're curious why, this demonstrates:
>>> a = b = []
>>> a.append(1)
>>> a
[1]
>>> b
[1]
他のヒント
Is there a reason you're not doing this?
a = b = c = d = e = f = g = h = i = j = None
I'm not too familiar with the intricacies of Python's syntax so please correct me if I'm wrong.
所属していません StackOverflow