簡體   English   中英

從python列表中的名稱(字符串)訪問對象屬性

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM