Appending to a new list for every loop

2019-07-21 05:15发布

问题:

I am running a for loop and appending a value into a list for every file run in loop. When I use append(), during the second run through the for loop it appends the new values into the same list as in the first run through loop. Is there a way to append and create a new list everytime it runs through loop?

phaseresult_i =[]
for i in range(len(folder)):
    data = np.loadtxt(dir + folder[i])
    time = data[:,0]-2450000
    magnitude = data[:,1]
    print ('File:', folder[i],'\n','Time:',time,'\n', 'Magnitude:', magnitude)
    print(len(time), len(magnitude))
    for t in range(len(time)):
        #print(t,time[t])
        floor = math.floor((time[t]-time[0])/Period)
        phase_i = ((time[t]-time[0])/Period)-floor
        phaseresult_i.append(phase_i)
    print(len(time), len(phaseresult_i))

The length of the array of time and length of array of phase result is not the same after the second time through loop.

回答1:

An mcve for creating a new list on each iteration of the outer loop then append to that list in the inner loop.

x = []
for n in range(4):
    q = []
    x.append(q)
    #other stuff
    for t in range(10):
        #other stuff
        q.append(t)

>>> from pprint import pprint       
>>> pprint(x)

[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]
>>>