试图弄清楚如何编写函数lookup(List),以便它在两个元素元组的列表中搜索元组的第一个元素。 我收到错误: 当我想为描述分配lookup(List)下的变量时,名称未定义。
def TupletoList():
List = []
menufun(List)
def menufun(List):
print("""
Alternatives
-----------
1. Insert
2. Search
3: Exit
""")
val = int(input("Choose an alternative by inputting its assigned number."))
if val == 1:
inputfun(List)
elif val == 2:
lookup(List)
elif val == 3:
funcex(List)
def inputfun(List):
b = input("Word")
for b in List:
if True:
print("The word is already in the list")
menufun(List)
else:
c = input("Description")
a = (b, c)
List.append(a)
print(List)
lookup(List)
def lookup(List):
d = input("Write the word you want to look up")
for d in List:
if True:
print(d, "means", #description)
def funcex(List):
exit()
答案 0 :(得分:2)
如果我正确理解,您的列表将包含一个(word, description)
元组,并且您希望您的查找功能提示输入一个单词,然后打印"<word> means <description>"
。如果是这种情况,我建议将您的查找功能更改为:
def lookup(List):
word = input("Write the word you want to look up")
for (w, d) in List:
if w == word:
print(w, "means", d)
这将遍历列表中的每个条目,并检查条目w
中的第一个值是否等于所需的单词。
List
作为变量名,因为它已经由python定义。像word_list
之类的东西似乎更合适。{ 'apple': 'this is a fruit', 'celery': 'this is a vegetable' }
。
if word in word_dict: print(word, word_dict[word])
)# Take input and assign it to b
b = input("Word")
# For every element in list, assign it to b and run the body.
for b in List:
# We've now lost our reference to our input word because we've reassigned b to the current element in the list.
# I'm assuming you want to check if our element is equal to the input word.
# This won't do that. This always evaluates to True meaning it will always print.
# You need to have some condition like input_word == b.
# My example lookup function shows a pretty similar situation.
if True:
print("The word is already in the list")
# Wouldn't necessarily recommend doing this.
# Using an explicit loop at the menu_fun would probably better.
menufun(List)
答案 1 :(得分:0)
您可以尝试将您的内容更改为以下内容:
def lookup(List):
d = input("Write the word you want to look up")
for x in List:
if x == d:
print(d, "means", "Some description")