[英]Python: Creating each item in a list as a variable and assigning a value to it in a for loop
In the below code I would like each item in the list to be created as a variable and then assigned a 'yes' or 'no' value.在下面的代码中,我希望将列表中的每个项目创建为变量,然后分配一个“是”或“否”值。 The loop should goes through each condiment succesfully, but keeps assigning a 'yes' or 'no' value, to 'i', rather than an item in the list, 'mayo' for example.循环应该成功地遍历每个调味品,但会不断将“是”或“否”值分配给“i”,而不是列表中的项目,例如“mayo”。 I thought perhaps having str(i) = pyip.inputYesNo(prompt + i +'?') but that doesn't seem to work either.我想也许有 str(i) = pyip.inputYesNo(prompt + i +'?') 但这似乎也不起作用。 How would I go about rectifying this?我将如何纠正这个问题?
Thanks谢谢
import pyinputplus as pyip
prompt = 'Do you want '
condiments = ['mayo', 'mustard', 'lettuce', 'tomato']
for i in condiments:
i = pyip.inputYesNo(prompt + i +'?')
There are multiple way you can go about that, my favorite would be the use of a dictionnary.有多种方法可以 go 关于那个,我最喜欢的是使用字典。
condiment_love = {}
for i in condiment:
condiment_love[i] = pyip.inputYesNo(f'do you love {i}?')
You can use locals() to create the variable.您可以使用 locals() 创建变量。
Try the following example to see how it works.试试下面的例子,看看它是如何工作的。
condiments = ['mayo', 'mustard', 'lettuce', 'tomato']
mylocals = locals()
for condiment in condiments:
mylocals[condiment] = input("Y or N: ")
print("mustard:", mustard)
print("locals:", locals())
Output: Output:
Y or N: n
Y or N: y
Y or N: n
Y or N: n
mustard: y
locals: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'condiments': ['mayo', 'mustard', 'lettuce', 'tomato'], 'mylocals': {...}, 'condiment': 'tomato', 'mayo': 'n', 'mustard': 'y', 'lettuce': 'n', 'tomato': 'n'}
Source: https://www.pythonforbeginners.com/basics/convert-string-to-variable-name-in-python资料来源: https://www.pythonforbeginners.com/basics/convert-string-to-variable-name-in-python
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.