问题描述
我正在运行 for 循环并将值附加到循环中运行的每个文件的列表中.当我使用 append() 时,在第二次运行 for 循环期间,它将新值附加到与第一次运行循环相同的列表中.有没有办法在每次循环运行时附加和创建一个新列表?
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.
推荐答案
一个 mcve,用于在外循环的每次迭代中创建一个新列表,然后在内循环中附加到该列表.
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]]
>>>
这篇关于为每个循环附加到一个新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!