[英]accessing PART of a file name based on user input to a function--Python
我是一名新手,試圖弄清楚如何完成以下任務:
我有以用戶命名的字典,格式如下:
<user>_hx
我想使用如下功能訪問它們:
def foo(user, other_stuff):
user_hx[key]
......等等。
我嘗試使用%進行訪問,如下所示:
def foo(user, other_stuff):
%r_hx %user[key]
但出於明顯的原因,我知道那是行不通的。
Adivce?
我想您要問的是如何基於表示其名稱的字符串訪問變量。 Python使這變得非常容易:
globals()['%s_hx' % user]
將為您提供變量<user>_hx
,因此您只需要
globals()['%s_hx' % user][key]
(我不確定您應該使用globals()
還是locals()
;這將取決於變量的定義方式以及嘗試從何處訪問它們)
就是說,可能有一種更容易/更干凈的方法來做您正在做的事情。 例如,您是否考慮過將所有這些字典放入“主”字典中,以便可以傳遞它們以及訪問它們
def foo(user,other_stuff):
fname = "%s_hx"%user[key] #not sure where key is comming from... but would result in something like "bob_hx"
with open(fname) as f:
print f.read()
也許?/
不要將名稱用作變量。 您可以將您的詞典集合放在另一個以這些名稱為關鍵字的頂級詞典中。
users = {
"user1_hx": {"name": "User 1"},
"user2_hx": {"name": "User 2"),
}
等等
然后訪問為:
realname = users["%s_hx" % name]["name"]
等等
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.