如何遍历Python列表中的文件的命令(循环)

时间:2019-06-20 12:57:38

标签: python

我是Python新手。我正在尝试编写一个简短的脚本。我想运行一个循环,在该循环中我必须读取许多文件,并为每个文件运行一个命令。特别是,我想对每个文件的两行进行计算并返回输出,该输出的名称被引用相对文件。

我能够将文件加载到列表中(“工作”)。我试图为计算编写第二个单循环,但我必须使用列表中的文件之一,它才能正确运行。问题是我无法遍历所有文件并无法从相对文件中获取每个“ integr”值。

让我展示我尝试做的事情:

import numpy as np

#I'm loading the files that contain the values whith which I want to do my calculation in a loop

work = {}
for i in range(0,100):
    work[i] = np.loadtxt('work{}.txt'.format(i), float).T

#Now I'm trying to write a double loop in which I want to iterate the second loop (the calculation) over the files (that don't have the same length) in the list

integr = 0

for k in work:
    for i in range(1, len(k[1,:])):
                  integr = integr + k[1,i]*(k[0,i] - k[0,i-1])

#I would like to print every 'integr' which come from the calculation over each file

print(integr)

当我尝试运行此消息时,出现此消息错误:

Traceback (most recent call last):
  File "lavoro.py", line 11, in <module>
    for i in range(1, len(k[1,:])):
TypeError: 'int' object has no attribute '__getitem__'

谢谢。

2 个答案:

答案 0 :(得分:1)

根据您想要的上下文进行猜测:

for k in work.values():

在字典上迭代只会产生键,而不会产生值。

答案 1 :(得分:1)

我有点猜测,但是如果我理解正确的话,您希望work成为列表,而不是 dictionary 。或者,也许您不想要它,但是一定可以使用给定的上下文列表而不是字典。
这是创建work列表的方式:

work = []
for i in range(0,100):
    work.append(np.loadtxt('work{}.txt'.format(i), float).T)

或使用上述循环的等效列表理解(通常列表理解更快):

work = [np.loadtxt('work{}.txt'.format(i), float).T for i in range(100)]

现在,您可以遍历work列表进行计算(我认为它们是正确的,我无法检查这一点):

for k in work:
    integr = 0
    for i in range(1, len(k[1,:])):
        integr = integr + k[1,i]*(k[0,i] - k[0,i-1])

请注意,我在循环内移动了integr = 0,因此每个文件都重新设置为0,否则每个内部循环将添加到先前内部循环的结果中。
但是,如果这是不正确的行为,请将integr = 0作为原始代码移到循环之外。