Appending to a new list for every loop

被刻印的时光 ゝ 提交于 2019-12-11 02:47:25

问题


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]]
>>>


来源:https://stackoverflow.com/questions/52542812/appending-to-a-new-list-for-every-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!