在Python中从元组提取字符串

在Python中从元组提取字符串,python,dictionary,tuples,Python,Dictionary,Tuples,我正试图用元组编一本字典。其思想是将单词及其描述存储在元组中。然后,元组进入一个列表。在那之后,我应该能够通过键入我想要描述的单词在字典中查找单词的意思 我的问题是仅从列表中提取元组的描述部分,并仅根据用户想要查找的单词打印该部分。我确实有一个函数,它似乎可以用来生成元组并将它们存储在列表中,但我认为这个函数也是错误的 这是我所能做到的: def tuples(): dictionary = [] while True: print("\n--- Menu fo

我正试图用元组编一本字典。其思想是将单词及其描述存储在元组中。然后,元组进入一个列表。在那之后,我应该能够通过键入我想要描述的单词在字典中查找单词的意思

我的问题是仅从列表中提取元组的描述部分,并仅根据用户想要查找的单词打印该部分。我确实有一个函数,它似乎可以用来生成元组并将它们存储在列表中,但我认为这个函数也是错误的

这是我所能做到的:

def tuples():
    dictionary = []
    while True:
    print("\n--- Menu for dictionary ---\n Choose 1 to insert a word\n Choose 2 to lookup a word\n Choose 3 to quit\n")
    answer = input("Write your answer here: ")
    if answer == "1":
        insert(dictionary)
    elif answer == "2":
        lookup(dictionary)
    elif answer == "3":
        break
    else:
        print("\nTry again!\n")

def insert(dictionary):
    word = input("What word would you like to add: ")
    des = input("Type a description of that word: ")
    info = (word, des)
    dictionary.append(info)

def lookup(dictionary):
    word = input("What word do you want to lookup: ")
    place = dictionary.index(word)
    print("\nDescription of", word,":", dictionary[place], "\n")

我认为你可以通过修改你的查找函数来实现你想要做的事情 使用来搜索查询的词典列表。我让您的示例对
lookup()
进行以下修改:


如果您关心运行时,我建议您将
(word,des)
元组抽象为一个类,这样您就可以使用字典作为字典,利用更快的查找速度。这也将解决重复条目的问题。

与另一个答案类似,本例循环检查元组的单词部分以获得描述部分。它在许多方面有所不同,但最重要的区别是它使用元组解包和订阅来获取元组的内容。为了说明关键概念,我省略了用户输入部分

注意:如果元组列表足够长,则需要考虑排序,并使用类似于<代码> BISTCTON//COD>标准库之类的东西来更有效地搜索和更新它。 例如:

dictionary = [("cat", "Four legs, scratches."), ("dog", "Four legs, wags."), ("gerbil", "Four legs, kangaroo-like.")]

def find_description(dictionary, search_term):
    # Note use of automatic tuple "unpacking"
    for word, description in dictionary:
        if word == search_term:
            print(f"Description of {word}: {description}")
            break
    else: # no-break
        print(f"Could not find {search_term} in dictionary.")

find_description(dictionary, "gerbil")
find_description(dictionary, "hamster")
输出:

Description of gerbil: Four legs, kangaroo-like.
Could not find hamster in dictionary.

为什么不直接使用没有元组的字典呢?如果你用这个词作为键,用描述作为值,不需要元组列表就可以解决你的问题,还是我遗漏了什么?是的,字典是我的下一个任务。但是这个任务是专门用元组来解决这个问题的:)我尝试了你的代码,但我只得到打印整个元组的代码。我想要的是程序在包含我要查找的单词的列表中找到元组,然后只打印元组的第二部分,即描述部分。
Description of gerbil: Four legs, kangaroo-like.
Could not find hamster in dictionary.