简体   繁体   中英

Printing all elements of list if string is in list?

So, I'm trying to make a search function which will print out all of the instances in a 2D list if the searched string is present in the list. So if the user searches for a term which is in the list, the program will return all the inner lists which have that term. This is what I have so far:

def music_library(tracks):
while True:
    st_search = raw_input("Search tracks: ")
    for a in tracks if st_search == tracks:
        print a

However, this is giving me a syntax error. I also don't know if this is doing what I want it do to. If anyone knows what I'm trying to do, I would appreciate the help!

You're close, I'd change it a little bit as follows.

def music_library(tracks):
    st_search = raw_input("Search tracks: ")
    for a in tracks:
        if st_search == a:
            print a

I'd write it like this

def find_track(albums, track):
    return [album for album in albums if track in album]

I have it tested in the interpreter, see if it is what you want

In [3]: albums = [['as','def','ded'], ['red','def','pil'],['ret','tre','yui']]

In [4]: def find_track(albums,track):
   ...:     return [album for album in albums if track in album]
   ...: 

In [5]: find_track(albums,'def')
Out[5]: [['as', 'def', 'ded'], ['red', 'def', 'pil']]

In [6]: find_track(albums,raw_input('Track? '))
Track? ded
Out[6]: [['as', 'def', 'ded']]

In [7]: 

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