【问题标题】:Search through list of tuples and display results搜索元组列表并显示结果
【发布时间】:2023-07-20 07:34:01
【问题描述】:

我有一个元组列表,我正在尝试搜索列表并显示包含搜索词的所有结果。到目前为止,我有这个:

holidays = []
holidays.append((1001,"Tenerife","Spain",2, 7, 80))
holidays.append((1002,"Cancun","Mexico",4, 14, 120))
holidays.append((1003,"Pairs","France",2, 3, 75))
holidays.append((1004,"Salzburg","Austria",3, 10, 90))
holidays.append((1004,"Madrid","Spain",3, 10, 90))enter code here

和:

search = input("Please enter a destination city or country to display all matching results: ")
    for item in holidays:
        if search in item:
           print ()
           print ("Here are all the results containing the word", search)
           print ()
           print ("Package ID:", item[0],":", item[1], "-", item[2],":",item[3], "person(s)",
           "for",  item[4], "nights costing" , "£" + str(item[5]), "pp/night")
           print ()
           menu = input("Press any key to return to the main menu:")

但如果我搜索西班牙,它只会显示包含西班牙这个词的第一个结果,而不是全部。我是否认为它应该显示包含搜索词的所有结果,因为它位于 for 循环中?

【问题讨论】:

  • input 将等待您按回车键,然后在第一个找到的结果后继续循环...我怀疑您想要去凹痕
  • 输入确实显示不止一个,只是你的 for 循环中有一个输入

标签: python list search tuples


【解决方案1】:

只需将两个第一个打印和第二个输入放在循环之外:

holidays = []
holidays.append((1001, "Tenerife", "Spain", 2, 7, 80))
holidays.append((1002, "Cancun", "Mexico", 4, 14, 120))
holidays.append((1003, "Pairs", "France", 2, 3, 75))
holidays.append((1004, "Salzburg", "Austria", 3, 10, 90))
holidays.append((1004, "Madrid", "Spain", 3, 10, 90))

search = input("Please enter a destination city or country to display all matching results: ")
print()
print("Here are all the results containing the word", search)
for item in holidays:
    if search in item:
        print()
        print("Package ID:", item[0], ":", item[1], "-", item[2], ":", item[3], "person(s)", "for",  item[4], "nights costing", "£" + str(item[5]), "pp/night")
menu = input("Press any key to return to the main menu:")

【讨论】:

  • 这将使程序在假期的每次迭代中停止。
  • 在我的示例中,我没有将 menu = input 行放在循环之外,而是放在 if 语句之外,无论如何现在都可以使用
  • 好吧,现在你修复它。
【解决方案2】:

就这样吧

print ()
print ("Here are all the results containing the word", search)
print ()
for item in holidays:
    if search in item:
        print ("Package ID:", item[0],":", item[1], "-", item[2],":",item[3], "person(s)",
        "for",  item[4], "nights costing" , "£" + str(item[5]), "pp/night")
        print ()
menu = input("Press any key to return to the main menu:")

当你在循环中完成搜索时会提示输入。

【讨论】: