Alternate to dynamically generate variable names with serial numbers in exec

Asked 2 years ago, Updated 2 years ago, 33 views

I'm a beginner at Python.

using the following sample No. 1_000.csv, No. 1_001.csv, No. 1_002.csv, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
It is stored in .
  

i=0
data = [ ]
while(i<141):
    data.append(pd.read_csv('No.1_%03d.csv'%i,sep=',',header=None))
    i+=1

But actually, I would like to change the No.1 part from No.1 to No.100 and replace csv.
I looked it up and found that it is possible to substitute data[] with data1[], data2[], ... in the exec function, but dynamic variables were not recommended, but only lists were recommended.

What should I do if I want to handle multiple variables at once without using the exec function like in this case?

python python3

2022-09-30 19:11

1 Answers

You can make a list.

data=[]
for n in range (1,101):
    wk = [ ]
    for i in range (141):
        wk.append(pd.read_csv('No.%d_%03d.csv'%(n,i), sep=',',header=None))
    data.append(wk)

data[0][0]#=>means data of No.0_000.csv'
data[4][120]#=>means data of No.4_120.csv'

If you don't want to do anything about it

data=[pd.read_csv('No.%d_%03d.csv'%(n,i), sep=',', header=None) for i in range(141)] for n in range(1,101)]

It would be fine.(If you can remember one day, that's fine)

I looked it up and found that it is possible to substitute data[] with data1[], data2[], ... in the exec function, but dynamic variables were not recommended, but only lists were recommended.

The reason why I don't want to do data1, data2,,, is because it's hard to use.


2022-09-30 19:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.