【问题标题】:Extracting a string from a tuple in Python从 Python 中的元组中提取字符串
【发布时间】:2021-04-28 16:49:06
【问题描述】:

我正在尝试使用元组制作各种字典。这个想法是将一个单词及其描述存储在一个元组中。然后元组进入一个列表。之后,我应该能够通过键入我想要描述的单词来在字典中查找单词的含义。

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

这是我所能达到的:

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

【问题讨论】:

  • 为什么不直接使用没有元组的字典呢?如果您使用单词作为键,使用描述作为值,那么如果不需要元组列表,那不会解决您的问题,还是我遗漏了什么?
  • 是的,字典是我的下一个任务。但是这个任务是专门用元组来解决问题的:)

标签: python dictionary tuples


【解决方案1】:

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

注意:如果元组列表足够长,您可能需要考虑对其进行排序并使用 bisect 标准库之类的东西来更有效地搜索和更新它。

例子:

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.

【讨论】:

    【解决方案2】:

    我认为您可以通过修改查找功能来实现您想要做的事情 使用generator expression 在字典列表中搜索查询。我让您的示例对lookup() 进行以下修改:

    def lookup(dictionary):
        word = input("What word do you want to lookup: ")
        place = next((i for i, v in enumerate(dictionary) if v[0] == word), None)
        print("\nDescription of", word,":", dictionary[place][1], "\n")
    
    

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

    【讨论】:

    • 我试过你的代码,但我只得到它来打印整个元组。我想要的是程序在包含我要查找的单词的列表中找到元组,然后只打印该元组的第二部分,即描述部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 2019-09-13
    • 2019-03-04
    • 2016-06-01
    • 2023-01-07
    • 2015-08-15
    相关资源
    最近更新 更多