在元组对列表中查找第一个元素

时间:2019-10-09 14:17:44

标签: python python-3.x

试图弄清楚如何编写函数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()

2 个答案:

答案 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")