如何检查一个元素是否在子列表中,然后打印子列表

How to check if an element is in a sub list, then print the sub list

我的程序要求用户输入关键字,如下所示:

search = input("Enter data name: ").upper()

    with open('schedule.txt', 'r') as f:
        list_of_lists = []
        for line in f:
            stripped_line = line.strip()
            line_list = stripped_line.split(',')
            list_of_lists.append(line_list)
        print(list_of_lists)
        for lists in list_of_lists:
            if search in lists:
                output = lists
                print('The available flights are:', *output, sep='\n')
            else:
                print('No flights found')
        f.close()

如果关键字存在于子列表中,那么我的程序将打印该子列表(可以在多个子列表中找到,因此需要多个输出)。然而,我现在遇到的问题是,输出不检查元素,它显示在一个长列表中,而不是换行分隔。

我的文本文件:

[1] MH371, MALAYSIAN AIRLINE, KUALA LUMPUR, BEIJING , 19-12-2021, N/A
[2] SX849, AIRASIA          , KUALA LUMPUR, BANGKOK , 05-01-2022, N/A
[3] MH234, MALAYSIAN AIRLINE, KUALA LUMPUR, LANGKAWI, 03-02-2022, N/A
[4] FD709, KOREA AIRLINE    , KUALA LUMPUR, SEOUL   , 29-12-2021, N/A
[5] Z1314, CATHAY AIRLINE   , KUALA LUMPUR, TOKYO   , 21-01-2022, N/A
[6] HY520, EMIRATES         , KUALA LUMPUR, TAIPEI  , 15-11-2021, N/A
[7] TT879, MALINDO AIR      , KUALA LUMPUR, HAWAII  , 08-02-2022, N/A

我的输出:

Enter data name: bangkok
[['[1] MH371', ' MALAYSIAN AIRLINE', ' KUALA LUMPUR', ' BEIJING ', ' 19-12-2021', ' N/A'], ['[2] SX849', ' AIRASIA          ', ' KUALA LUMPUR', ' BANGKOK ', ' 05-01-2022', ' N/A'], ['[3] MH234', ' MALAYSIAN AIRLINE', ' KUALA LUMPUR', ' LANGKAWI', ' 03-02-2022', ' N/A'], ['[4] FD709', ' KOREA AIRLINE    ', ' KUALA LUMPUR', ' SEOUL   ', ' 29-12-2021', ' N/A'], ['[5] Z1314', ' CATHAY AIRLINE   ', ' KUALA LUMPUR', ' TOKYO   ', ' 21-01-2022', ' N/A'], ['[6] HY520', ' EMIRATES         ', ' KUALA LUMPUR', ' TAIPEI  ', ' 15-11-2021', ' N/A'], ['[7] TT879', ' MALINDO AIR      ', ' KUALA LUMPUR', ' HAWAII  ', ' 08-02-2022', ' N/A']]

如您所见,它打印整个列表,而不仅仅是元素所在的子列表

你可以看看这个词是否在行中然后将它转换成一个列表并输出:

search = input("Enter data name: ").upper()

with open('filename.csv') as input_file:
    for line in input_file:
        sublist = list(map(str.strip, line.split(',')))
        if search in sublist:
            print(sublist)

输出:

>>> Enter data name: bangkok
['[2] SX849', 'AIRASIA', 'KUALA LUMPUR', 'BANGKOK', '05-01-2022', 'N/A']

正如@Jab 已经指出的正确答案,我会更正你的错误,以帮助你完成作业

在你的第 9 行到第 13 行的代码中:

for lists in list_of_lists:
    if search in lists:
        output = lists
        print('The available flights are:', *output, sep='\n')

lists 变量将等于:

[1] MH371, MALAYSIAN AIRLINE, KUALA LUMPUR, BEIJING , 19-12-2021, N/A

在第一个 运行 中,您真正搜索的是字符串列表,而不仅仅是像“KUALA LUMPUR”这样的字符串

所以,为了更正您可以使用 2 个循环而不是一个循环来访问内部元素。

像这样:

for lists in list_of_lists:
        for elements in lists:
            if search in elements:  
                output = lists
                print('The available flights are: \n', *output, sep='')