【问题标题】:How to let python to look for a specific keyword and print out that particular list that includes that keyword from a major list. (2D list)如何让 python 查找特定关键字并从主要列表中打印出包含该关键字的特定列表。 (二维列表)
【发布时间】:2021-12-23 03:39:56
【问题描述】:

我是 python 的初学者。我遇到了一个难题,我试图在 python 中创建一个搜索函数而不导入任何东西,在成功搜索后我希望它从主要列表中打印出那个次要列表。

在这个例子中: [['Darren', '19'], ['John', '17'], ['Dave', '16']] #['name', 'age']

输入要搜索的名称:Dave #Example input

找到了,Dave 16 #Expected Output

下面是我写的代码:

'''

定义搜索名称():

with open("namelist.txt") as f:
    datafile = f.read()
found = False

name = input("Enter name: ")

while True:
    if name in datafile:
        print("found")

        CleanData = [] 
        #CleanData = [['Darren', '19'], ['John', '17'], ['Dave', '16']]
        h = open("namelist.txt", "r")
        for record in h:
            stripped = record.strip()
            recordlist = stripped.split("\t")
            CleanData.append(recordlist)
        h.close()

        print(?)                            #Place where i'm stuck

        found = True
        return True

    else:
        print("User nor found")
        break

'''

任何知道如何做到这一点的人请发表评论以解决这个问题????,我已经研究了我遇到的问题,但仍然没有解决......做得够多了,或者我一直在寻找错误的材料来学习

【问题讨论】:

    标签: python list search multidimensional-array


    【解决方案1】:

    像这样:

    names = [['Darren', '19'], ['John', '17'], ['Dave', '16']]
    search = input("Enter Name to search:")
    for i in range(0, len(names)):
        if search in names[i]:
            print("found, {} {}".format(names[i][0], names[i][1]))
            break
    

    循环检查每个列表以查看它是否包含正确的名称,当找到正确的列表时,将其打印出来并退出循环。

    【讨论】:

    • 天哪,你是救生员。通过使用您建议的代码,现在它可以工作了!!!非常感谢你
    • 不客气 :)
    猜你喜欢
    • 2021-12-06
    • 1970-01-01
    • 2020-08-21
    • 2018-10-05
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    相关资源
    最近更新 更多