如何在字符串列表中搜索变量
我对Python的知识非常基础。这是我目前写的代码:当我运行这段代码时,出现了错误 UnboundLocalError: local variable 'response' referenced before assignment on line 7
。我想创建一个函数,用来比较输入的响应和两个列表,如果找到了这个输入,就把真或假赋值给响应。我还需要把这个响应(应该是真或假)赋值给另一个答案列表。(真或假会被赋予具体的值,然后计算这个答案列表的总和,以便与最终的列表计算匹配)。
response = [str(input("Would you rather eat an apple or an orange? Answer apple or orange."))]
list1 =[str("apple"), str("Apple"), str("APPLE")]
lsit3 = [str("an orange"), str("Orange"), str("orange"), str("an Orange"), str("ORANGE")]
def listCompare():
for list1[0] in list1:
for response[0] in response:
if response[0] == list1[0]:
response = true
else:
for list3[0] in list3:
for response[0] in response:
if response[0] == list3[0]:
response = false
listCompare()
**编辑:好的,谢谢你们的调侃。我还在上高中,正在上一个非常基础的课程。我只是想让这个代码能运行,以便通过这门课。我不需要“帮助”了。
相关问题:
- 暂无相关问题
2 个回答
0
与其列出所有可能的确切答案,不如对可能的答案进行模式匹配。下面是一种不区分大小写的匹配方法:
import re
known_fruits = ['apple', 'orange']
response = str(input("What would you like to eat? (Answer " + ' or '.join(known_fruits) + '): '))
def listCompare():
for fruit in known_fruits:
pattern = '^(?:an\s)?\s*' + fruit + '\s*$'
if re.search(pattern,response,re.IGNORECASE):
return True
if listCompare():
print("Enjoy it!")
else:
print("'%s' is an invalid choice" % response)
这样可以匹配到 apple
、Apple
,甚至 ApPle
。它还可以匹配到 'an apple'。不过,它不会匹配 pineapple
。
下面是相同的代码,不过把正则表达式拆解开来讲:
import re
known_fruits = ['apple', 'orange']
print("What would you like to eat?")
response = str(input("(Answer " + ' or '.join(known_fruits) + '): '))
# Change to lowercase and remove leading/trailing whitespace
response = response.lower().strip()
def listCompare():
for fruit in known_fruits:
pattern = (
'^' + # Beginning of string
'(' + # Start of group
'an' + # word "an"
'\s' + # single space character
')' + # End of group
'?' + # Make group optional
'\s*' + # Zero or more space characters
fruit + # Word inside "fruit" variable
'\s*' + # Zero or more space characters
'$' # End of the string
)
if re.search(pattern,response):
return True
if listCompare():
print("Enjoy it!")
else:
print("'%s' is an invalid choice" % response)
2
你在这里把事情弄得很复杂,不过如果你是编程新手或者刚接触Python,这也是可以理解的。
为了让你走上正轨,这里有一个更好的解决问题的方法:
valid_responses = ['a', 'b']
response = input("chose a or b: ").lower().strip()
if response in valid_responses:
print("Valid response:", response)
else:
print("Invalid response:", response)
如果有任何你不理解的函数,可以在这里查找。
字符串的声明也可以用单引号或双引号来表示:
my_strings = ['orange', "apple"]
另外,要在函数内部给全局变量赋值,你需要使用global这个关键词。
my_global = "hello"
def my_fuction():
global my_global
# Do stuff with my_global
在for循环中应该给新的局部变量赋值:
options = ['a', 'b', 'c']
for opt in options:
print(opt)