我正在构建的脚本的一部分要求我将用户输入映射到列表(可能的输入),然后将其关联到字典中的键(结果)。我已经设法获得结果,但我想知道有没有更好的方法可以解决这个问题?
user_input = "bought"
output = None
input_mapping = {"buy": ["bought", "buys", "purchased"],
"sell": ["sold", "sells", "sale"]}
for key, values in input_mapping.items():
if user_input in values:
output = key
print(output)
输入输出:
user_input = "sale"
>>> sell
user_input = "bought"
>>> buy
非常感谢!