附加到每个循环的新列表 [英] Appending to a new list for every loop

查看:85
本文介绍了附加到每个循环的新列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个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,然后将其附加到内循环的该列表中。 / p>

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

这篇关于附加到每个循环的新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆