我有这段代码:
if opt1 is not None:
user_a, db_a = opt1.split("/")
db_a = country_assoc(int(db_a))
client_a = Client(None, user_a, db_a)
data_client_a = client_a.get_user()
if opt2 is not None:
user_b, db_b = opt2.split("/")
db_b = country_assoc(int(db_b))
client_b = Client(None, user_b, db_b)
data_client_b = client_b.get_user()
....
但是,我想用循环生成类似的结构。
这样做的正确方法是什么?我正在尝试这个
abcde = ['a', 'b', 'c', 'd', 'e']
for idx, val in enumerate(abcde):
if opt+idx is not None:
user_+val, db_+val = opt+idx.split("/")
db_+val = country_assoc(int(db_+val))
client_+val = Client(None, user_+val, db_+val)
data_client_+val = client_+val.get_user()
答案 0 :(得分:5)
我不明白为什么人们觉得有必要尝试这样做。变量名称不是数据。从来没有充分的理由动态创建变量名称。
只需将您的值放在字典或列表中即可。
for idx, val in enumerate(abcde):
if opts[idx] is not None:
user, db = opts[idx].split("/")
users[val] = user
dbs[val] = country_assoc(int(db))
clients[val] = Client(None, user, db)
data_clients.append(clients[val].get_user())
答案 1 :(得分:0)
a = [opt1, opt2, opt3, opt4, opt5]
data_clients = []
for j in a:
if j is not None:
user, db = j.split("/")
db = country_assoc(int(db))
client = Client(None, user, db)
data_clients.append(client.get_user())