Python - 使用带有自定义变量命名的for循环

时间:2017-09-21 08:54:05

标签: python for-loop

我正在尝试用 Python 做一个(思考)相当简单的任务,但似乎无法做到或找到一种方法来做到这一点。我正在尝试使用for循环,其中我的变量设置为具有自定义数字的另一个变量。这有点难以解释,但我的代码会更好地解释它:

aha_aha1 = "1"
aha_aha2 = "wouh"
aha_aha3 = "yes !"
test = "my man !"

for i in range (0, 4):
  if aha_aha{i} = "yes !":
     test[i] == aha_aha{i}.format(i)

我希望test[i]仅在满足某些条件时才aha_aha[i],但上面的代码显然不起作用。有什么帮助吗?

3 个答案:

答案 0 :(得分:1)

如果你真的想要那些'aha_x's:

d = {"aha_aha1" : "1", "aha_aha2" : "wouh", "aha_aha3" : "yes !"}
test = "my man !"

for i in range (0, 4):
  temp = "aha_aha"+str(i)
  if d.get(temp) == "yes !":
    #Do something

答案 1 :(得分:0)

实际上,我不明白你在做什么,但至少从这里开始:

aha_aha_list = ["1", "wouh", "yes !"]
test = "my man !"

for aha_aha in aha_aha_list:
    if aha_aha is "yes !":
        test = aha_aha

print(test)

输出:

yes !

答案 2 :(得分:0)



do you want that?in python str type is unable to change,so you should chage str to list,and then chat list to str.
d = {'aha_aha1': '1', 'aha_aha2': 'wouh', 'aha_aha3': 'yes !'}
test = "my man !"
for i in range(0, 4):
    if d.get("aha_aha{i}".format(i=i),None) == "yes !":
        test = list(test)
        test[i] = d.get("aha_aha{i}".format(i=i))
        test = ''.join(test)
        
        
   print(test) #my yes !an !