[英]Accessing object attributes from name (string) inside a list in python
I am running a python script that generates multiple variables after iterating over multiple directories. 我正在运行一个python脚本,该脚本在遍历多个目录后生成多个变量。 After the script has run, I want to perform some operations on a few dataframes whose names match a specific pattern: 脚本运行后,我想对名称与特定模式匹配的几个数据框执行一些操作:
failed_runs_finder = re.compile(r'FAILEDRuns_') # pattern to search
list_dfs = list(filter(failed_runs_finder.findall, dir())) # puts the matching results in a list
Which gives me a list as shown below: 这给了我一个清单,如下所示:
['FAILEDRuns_0112',
'FAILEDRuns_0121',
'FAILEDRuns_0126',
'FAILEDRuns_0129',
'FAILEDRuns_0131',
'FAILEDRuns_0134',
'FAILEDRuns_0135',
'FAILEDRuns_0137',
'FAILEDRuns_0142',
'FAILEDRuns_0153',
'FAILEDRuns_0165',
'FAILEDRuns_0171',
'FAILEDRuns_0175']
If I now try to access the number of rows and columns from each of the elements in list_dfs
with the shape()
method with the following loop: 如果我现在尝试使用shape()
方法通过以下循环list_dfs
每个元素的行数和列数:
for i in list(filter(failed_runs_finder.findall, dir())):
print(getattr(i, 'shape'))
I get: 我得到:
AttributeError: 'str' object has no attribute 'shape'
This is because the elements in list_dfs
are, as the error suggests, strings , and not the dataframes themselves. 这是因为如错误所示, list_dfs
中的元素是字符串 ,而不是数据帧本身。
My question is then how can I access the objects themselves by their names inside a list? 我的问题是然后如何通过列表中的对象本身访问对象?
不知道我是否正确要做什么,但是您可以使用字典将字符串与数据框映射,例如:
{'FAILEDRuns_0112': FAILEDRuns_0112}
This should do the trick: 这应该可以解决问题:
for i in list(filter(failed_runs_finder.findall, dir())):
print(locals()[i].shape)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.