Python 从嵌套for循环中提取变量
我试图循环浏览多个文件,并从每个文件中提取一个计算变量作为其自己的变量名(即max_值[1]、max_值[2]、…)。当前正在使用字典存储每个变量Python 从嵌套for循环中提取变量,python,dictionary,for-loop,Python,Dictionary,For Loop,我试图循环浏览多个文件,并从每个文件中提取一个计算变量作为其自己的变量名(即max_值[1]、max_值[2]、…)。当前正在使用字典存储每个变量 ### Create dictionary max_value = dict() ### Loop through files using glob for file in glob.glob('files'): ### Do calculations using file variables calculated_value = 1
### Create dictionary
max_value = dict()
### Loop through files using glob
for file in glob.glob('files'):
### Do calculations using file variables
calculated_value = 10
### Store calculated value in dictionary
for x in range(1,num_files+1):
max_value[x] = calculated_value
但是,嵌套的for循环将用最后一个文件的计算值覆盖先前保存的max_值。如何避免从上一个文件的max_值重写字典中的每个max_值?我想这就是您想要的:
### Create dictionary
max_value = dict()
### Loop through files using glob
for i, file in enumerate(glob.glob('files')):
### Do calculations using file variables
calculated_value = 10
### Store calculated value in dictionary
max_value[i] = calculated_value
我想这就是你想要的:
### Create dictionary
max_value = dict()
### Loop through files using glob
for i, file in enumerate(glob.glob('files')):
### Do calculations using file variables
calculated_value = 10
### Store calculated value in dictionary
max_value[i] = calculated_value
您从不更新num_文件,所以您会一直覆盖自己的数据。您从不更新num_文件,所以您会一直覆盖自己的数据。是否使用另一个容器作为字典值?很难说得更多,你到底想要什么?看起来最里面的循环只是在
max\u value
中向每个键写入computed\u value
。您正在寻找的行为是什么?您正在使用一个从未声明的变量名称num\u files
。这个值是多少?请给出一个你想要的输出的例子。从阅读这段代码中,根本不清楚您试图做什么。是否使用另一个容器作为字典值?很难说得更多,你到底想要什么?看起来最里面的循环只是在max\u value
中向每个键写入computed\u value
。您正在寻找的行为是什么?您正在使用一个从未声明的变量名称num\u files
。这个值是多少?请给出一个你想要的输出的例子。从阅读这段代码中,根本不清楚您试图做什么。