[英]Accessing object attributes from name (string) inside a list in python
我正在运行一个python脚本,该脚本在遍历多个目录后生成多个变量。 脚本运行后,我想对名称与特定模式匹配的几个数据框执行一些操作:
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
这给了我一个清单,如下所示:
['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']
如果我现在尝试使用shape()
方法通过以下循环list_dfs
每个元素的行数和列数:
for i in list(filter(failed_runs_finder.findall, dir())):
print(getattr(i, 'shape'))
我得到:
AttributeError: 'str' object has no attribute 'shape'
这是因为如错误所示, list_dfs
中的元素是字符串 ,而不是数据帧本身。
我的问题是然后如何通过列表中的对象本身访问对象?
不知道我是否正确要做什么,但是您可以使用字典将字符串与数据框映射,例如:
{'FAILEDRuns_0112': FAILEDRuns_0112}
这应该可以解决问题:
for i in list(filter(failed_runs_finder.findall, dir())):
print(locals()[i].shape)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.