简体   繁体   中英

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)

i'm a beginner in python. I've met a diificulty where I'm trying to create a search function in python without importing anything, where upon a succesful search i want it to print out that minor list out of a major list.

In this example: [['Darren', '19'], ['John', '17'], ['Dave', '16']] #['name', 'age']

Enter Name to seach: Dave #Example input

found, Dave 16 #Expected Output

Below are the codes, I've written:

'''

def searchName():

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

'''

Anyone that knows how to make this happen pls leave a comment about solving this 😭, I've done researches about the prob i'm having but still no luck solving..... maybe i've not done enough or i've been searching wrong materials to study

Like this:

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

The loop checks each list to see if it contains the correct name, and when it finds a list that does, it prints it out and exits the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM