搜索元组列表并显示结果

时间:2018-11-25 17:00:49

标签: python list search tuples

我有一个元组列表,我试图在该列表中进行搜索并显示包含搜索项的所有结果。到目前为止,我有这个:

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循环中?

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

就这样吧

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

在循环中完成搜索后,输入将提示。