python implements the operation of loop definition and assignment of multiple variables
- 2021-09-20 20:56:48
- OfStack
exec function, which can be cyclically defined and assigned to multiple variables
exec ("temp%s=1"%1)
This code means that exec executes temp1=1. The% s in the string is replaced by '1'.
We can define multiple variables by setting another loop outside.
for i in range(10):
exec ("temp%s=1"%i)
Here, 10 variables are generated in one loop, and i varies from 0 to 9. The variable i replaces% s, so in each loop, temp0, temp1, temp2... are assigned a value of 1.
If you want to replace multiple placeholders, you can write this:
exec ("temp%s=%d"%(i,i))
Here, replace placeholders in the form of strings and integers, respectively, and execute the results:
temp1=1
Supplement: 1 series of results in Python loop statement are assigned to 1 series of variables, and exec function
Using Tools:
exec function, placeholder
Situation note:
k is a multilevel nested list # k. shape (9, 101, 4)
Generate 9 DataFrame formats according to K, with variable names k1, k2 … k9
from pandas import DataFrame
for i in range(k.shape[0]):
exec ("k%s=DataFrame(k[%s])"%(i,i))
The use of # placeholders is the same as in print ().
The # exec function can also be used to handle variables with formatted variable names in for statements.