简体   繁体   中英

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. 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:

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM