[英]How to point to a variable dynamically using str to update its value
我想更新一些他們命名的列表
ACL = []
ANL = []
APL = []
# more around 50+
我在元組中也有這些名稱的 str 形式
CHOICES = [ 'ACL', 'ANL', 'APL' ]
現在,當我得到 ACL 的結果時,我正在對數據庫進行查詢,我想更新 ACL 列表。 查詢數據並將其附加到列表中沒有問題。 但我的問題是我必須單獨查詢和 append 每個列表。 但我想利用這些選擇,迭代它們並更新相對列表
這是我目前的做法:
acl_filtered_data = [{"results" : "result"} for j in qs if j.choice == 'ANL']
ACL.append(acl_filtered_data)
其他選擇也是如此。
所以在這里我想為所有可用的選擇運行一個循環,並將 append 放入相關列表中。
for i in CHOICES:
filtered_data = [{"results" : "result"} for j in qs if j.choice == i]
# here I want to point ACL = [] and append it with the filtered_data and also keep repeating for the others
# I'm not sure how I can do that.
我需要你的幫助來實現這種邏輯。 謝謝
像以前一樣創建字典或元組列表,其中每個字符串都引用相應的列表。
然后在每次迭代中,您都會引用 append 所需的列表。
ACL = []
ANL = []
APL = []
CHOICES = {'ACL': ACL, 'ANL': ANL, 'APL': APL}
...
for key, value in CHOICES.items():
filtered_data = [{"results" : "result"} for j in qs if j.choice == key]
value.append(filtered_data)
或者使用元組。
ACL = []
ANL = []
APL = []
CHOICES = [('ACL', ACL), ('ANL', ANL), ('APL', APL)]
...
for text, lst in CHOICES:
filtered_data = [{"results" : "result"} for j in qs if j.choice == text]
lst.append(filtered_data)
為此,您可以使用eval() function。 您可以將任何 Python 語句作為字符串傳遞到eval() function 中,它將被執行。 請參閱下面的示例(從官方文檔中獲取),
>>> x = 1
>>> eval('x+1')
2
通過此示例,您可以通過更改單行代碼來使用自己的代碼。
ACL = []
ANL = []
APL = []
CHOICES = [ 'ACL', 'ANL', 'APL' ]
for i in CHOICES:
filtered_data = [{"results" : "result"} for j in qs if j.choice == i]
eval(f'{i}.append({filtered_data})')
這將動態更新您的列表。 語句eval(f'{i}.append({filtered_data})')
類似於,
ACL.append(filtered_data)
ANL.append(filtered_data)
APL.append(filtered_data)
請參閱這篇Python eval()文章以獲得一些實踐經驗。
它認為您正在尋找的是vars([object]) :
ACL = []
ANL = []
APL = []
# E.g. get a reference to ACL using vars():
x = vars()['ACL']
# x is now a reference to ACL
# As lists are mutable, any operation on x will directly change ACL
print(x is ACL)
x.append('test')
print(ACL)
# Now we switch to ANL for example
x = vars()['ANL']
# Now any operation on x changes ANL
print(x is ANL)
x.append('test2')
print(ANL)
print(ACL)
一種更簡單、更直觀的方法是將數據存儲在字典中:
# Store data in a dictionary
data = {
'ACL': [],
'ANL': [],
'APL': [],
}
# The keys of the dictionary are the valid choices
CHOICES = list(data.keys())
# Now you can simply index your data by the name of the according list:
data['ACL'].append('test')
print(data['ACL'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.