Home > front end >  Extract items from 2D list
Extract items from 2D list

Time:10-20

I have the following 2D list

listItem = [["Apple", "TP123", "67", "77"], [
"Orange", "TP223", "55", "66"], ["Banana", "TP777", "98", "88"], ["Cherry", "TP123", "98", "88"]]

I want to compare the user input with the second element in each list in the listItem and print out the whole list if the value matches. If the value doesn't match, I will ask the user to enter the value again and again.

Here is my code:

def repeat():
    tp = input("Please enter your tp: ")
    for i in range(len(listItem)):
        if tp == listItem[i][1]:
            print(listItem[i])
            break
    else:
        repeat()

I am facing some problems here. In the listItem, there are two "TP123". However, if the user enters "TP123", it only prints out one result instead of two. But if I didn't use the break, the code will keep asking users to enter another value even though the value they enter matches.

I am a python beginner, can anyone help me to solve this problem, thank you very much.

CodePudding user response:

You are breaking before it can find the next item. Also no need to use range just loop through the list.

def repeat():
    tp = input("Please enter your tp: ")
    print(*(i for i in listItem if i[1] == tp), sep='\n')

Or in full for loop:

def repeat():
    tp = input("Please enter your tp: ")
    for i in listItem:
        if tp == i[1]:
            print(i)

CodePudding user response:

Use an extra variable and set it to True if their are matches, and use an if statement to trigger the repeat function again if it's False:

And also better without range:

def repeat():
    tp = input("Please enter your tp: ")
    match = False
    for i in listItem:
        if tp == i[1]:
            print(i)
            match = True
    if not match:
        repeat()
  • Related