What should I do when I decide on repetitive variables?

Asked 2 years ago, Updated 2 years ago, 19 views

 variable 1 = 'Hong Gil-dong'
Variable 2 = 'Kim Gap-hwan'
..
Variable n = 'Long'
========================
Variable 1_1 = 'Hong Gil-dong'
Variable 1_2 = 'Kim Gap-hwan'
Variable 2_1 = 'Listening'
..
Variable n_n= 'Long'

After the variables, 1_n, 1_1, 1_2 n_n ... When you make a variable, you don't put it in one by one I wonder if there is a way to make a variable and substitute the value.

list = ["Hong Gil-dong", "Kim Gap-hwan"...]
for i in range(10):
    Variable {}.format(i) = list[i]

python

2022-09-22 19:28

1 Answers

You can use the reflection function

Python is managed by dict when paired, such as 'name' and 'value', as in variables.

>>> import sys
>>> mod = sys.modules[__name__]
>>> L = ["Hong Gil-dong", "Kim Gap-hwan"]
>>> for k, v in enumerate(L):
...     ...     setattr(mod, 'v{}'.format(k), v)
...     
>>> v0
"Hong Gil Dong."
>>> v1
"Kim Gap Hwan."
>>> globals()
{'L':'Hong Gil-dong','Kim Gap-hwan',
 '__builtins__': <module 'builtins' (built-in)>,
 '__doc__': None,
 '__loader__': <class '_frozen_importlib.BuiltinImporter'>,
 '__name__': '__main__',
 '__package__': None,
 '__spec__': None,
 'k': 1,
 'mod': <module '__main__' (built-in)>,
 'pyscripter': <module 'pyscripter'>,
 'sys': <module 'sys' (built-in)>,
 'v': 'Kim Gap Hwan',
 'v0': 'Hong Gil Dong',
 'v1: Kim Gap-hwan'}


2022-09-22 19:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.