Gloria Bazargan Gloria Bazargan - 8 months ago 59
Python Question

Looping to assign list of lists into arrays

I have a list of lists and I want to assign each of the sublists to an array of shape a particular shape. So far I have:


# read the file in lines
with open('','r') as f:
lines =

# Split the whole file into a list of lists
profiles = [lines[i:i + N] for i in xrange(0, len(lines), N)]

#Convert first sublist to array skipping the first two lines
set1 = np.genfromtxt(profiles[0],skip_header=2,usecols=[1,2,3])

Is there a way I can generate a bunch of arrays named "set_n" where n would be an indexing variable and have something along the lines of:

for n in range (4000):
set_n = np.genfromtxt(profile[n], skip_header=2, usecols=[1,2,3])


The best solution is to use a dictionary as follows:

my_dict = {}

for n in range (4000):
      my_dict['set_{}'.format(n)] = np.genfromtxt(profile[n], skip_header=2, usecols=[1,2,3])

Now, instead of using set_1, set_2, etc you can use my_dict['set_1'], my_dict['set_2'], etc