我正在做一个搜索功能,该功能使用用户输入生成条件,然后将这些条件应用于字典,并需要一种方法来静态地存储用户输入,同时重用变量user_input。
当我使用以下示例时,它用最近的输入替换了我以前的输入。因此,如果我先写“苹果名称”然后“退出”,它将搜索名称中带有“ u”的项目,因为user_input现在为“ quit”,而user_input [1]现在为“ u”。
简单的解决方法是在变量之间放置一个变量,然后将其用作条件,例如: user_input [1] == name_var condition.append(lambda x:x ['name']中的name_var) 不起作用,因为我经常想要一个不包含x,y或z的名称,并且将其简化为不包含z的名称。
dictionary = {
'pineapple':{'name':'pineapple', 'type':'fruit'},
'apple':{'name':'apple', 'type':'fruit'},
'Stephan Hawking':{'name':'Stephan Hawking', 'type': 'vegetable'}
}
conditions = []
while True:
user_input = input('>>> ')
if user_input == 'quit':
break
user_input = user_input.split(' ')
if user_input[0] == 'name':
conditions.append(lambda x: user_input[1] in x['name'])
if user_input[0] == 'type':
conditions.append(lambda x: x['type'] == user_input[1])
print(user_input[1])
for key in dictionary:
element = dictionary[key]
for condition in conditions:
if not condition(element):
print(key, 'failed the test')
输入: 苹果名字 '放弃' 预期产量: 斯蒂芬·霍金(Stephan Hawking)考试不及格 实际输出: 菠萝考试不及格 “苹果未通过测试” “斯蒂芬·霍金考试不及格”