简体   繁体   中英

Searching through a 2D list?

I have a 2D list that contains a list of lists of music info like so:

tracks = [(The Beatles, Yellow Submarine), (Green Day, American Idiot)]

I'm trying to make a function that will ask the user for a string and then the function will look through the list and show ALL the inner lists with the string inside of it. This is my current function which does not work.

    if response == "st":
        st_search = raw_input("Search tracks: ")
        return [ t for t in tracks if st_search in tracks ]
    elif response == "sa":
        sa_search = raw_input("Search artists: ")
        return [ ar for ar in tracks if s_search in tracks ]

If anyone understand what I'm trying to do and can help, it would be greatly appreciated!

EDIT: The 2D music list is extremely larger than the example given

Aside from your first code snippet having invalid syntax, your search function is most of the way done. In your generator you should check against the current entry for a match, instead of the whole list:

if response == "st":
    st_search = raw_input("Search tracks: ")
    return [ t for t in tracks if st_search==t[1] ]
elif response == "sa":
    sa_search = raw_input("Search artists: ")
    return [ t for t in tracks if sa_search==t[0] ]

This will return all (artist,track) pairs from the list that match the query.

Ideally, you do not want to hardcode your variables into your variables. That way, it may become prohibitive to change the data structure. You might consider the following code:

ind = { 'sa': 0, 
        'st': 1 }
st_search = raw_input("Search tracks: ")
return filter( lambda m: m[ind[response]] == st_search , tracks )

Here, if the datastructure changes from

tracks = [('The Beatles', 'Yellow Submarine'), 
          ('Green Day',   'American Idiot')]

to

tracks = [('The Beatles', 'Yellow Submarine',  'Yellow Submarine'),
          ('The Beatles', 'All Together Now',  'Yellow Submarine'), 
          ('Green Day',   'American Idiot',    'American Idiot'  ), 
          ('Green Day',   'Jesus of Suburbia', 'American Idiot'  )
          ]

The only change you will need to do is in the ind ex variable by the way of:

ind = { 'sa': 0, 
        'st': 1,
        'al': 2 }

And now you can check by album as well. Of course, you will have to check that the response is in ind , but thats just an additional if statement ...

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