Home > Software design >  Python- search through multiple arrays and print entire list if desired element is found
Python- search through multiple arrays and print entire list if desired element is found

Time:12-06

Here is my current code:

search=input('Enter a book title')

def read_book():
    booksdata=[]
    f=open('books2.txt', 'r')
    for record in f:
        cleanrecord=record.strip()
        books=cleanrecord.split(',')
        booksdata.append(books)
    f.close()
    return booksdata

read_book()

It opens up a text file that has data stored like this:

1, The Hunger Games, Adventure, Suzanne Collins, 1/08/2006, coai
2, Harry Potter and the Order of the Phoenix, Fantasy, J.K Rowling, 25/09/2021, ajyp

Im trying to program it so if the user types in 'Hunger', the entirety of the list(s) that contains hunger will get printed out:

['1', ' The Hunger Games', ' Adventure', ' Suzanne Collins', ' 1/08/2006', ' coai']

CodePudding user response:

You need to check if your input is it in every row

search=input('Enter a book title')

def read_book():
    booksdata=[]
    f=open('books2.txt', 'r')
    for record in f:
        if search in record: # check
            cleanrecord=record.strip()
            books=cleanrecord.split(',')
            booksdata.append(books)
    f.close()
    return booksdata

result = read_book()
print (result) 

output:

 [['1', ' The Hunger Games', ' Adventure', ' Suzanne Collins', ' 1/08/2006', ' coai']]

CodePudding user response:

for d in read_book():
    if any(['hunger' in w.lower() for w in d]):
        print(d)

The function any() takes in a list of booleans as argument and returns True if any of the value is true. The list that we are giving it stores, for every element in d, whether the string 'hunger' is present in (is a substring of) that element.

  • Related