0

Im reading over an itunes library file. I scraped the artist names and songs and put them in parallel lists, one containing artist names and another containing artist songs. I would like to do this by using only lists

artist_choice = input("Enter artist name: ")
artist_names = [Logic, Kanye West, Lowkey, Logic, Logic]
artist_songs = [Underpressure, Stronger, Soundtrack to the struggle, Ballin, Im the man]

Say the user inputs the artist name Logic, how would i loop through the parallel list and print out every song associated with the artist Logic? if the user entered Logic the output should be:

Underpressure
Ballin
Im the man
shahaadn
  • 1
  • 6
  • I'd search for all index's of logic and then use those index values to find your results, only need to search through one array, not both at the same time. – rich green Feb 26 '15 at 19:51
  • If you zip the lists together, you can iterate over them at the same time. Then you can just use a predicate to set what's printed. I would reorganize the way your storing things though. What about storing the information in a tuple like `(artist_name, [artist's_songs])`. Then you can just store a list of these tuples, and go into an artist's tuple to fetch their songs. If you're adding more fields then songs, I'd create a class to store the data. – Carcigenicate Feb 26 '15 at 19:51
  • @richgreen how would i find the index position of every occurrence of logic? i figured how to do the index of only the first occurence – shahaadn Feb 26 '15 at 19:57
  • http://stackoverflow.com/questions/209840/map-two-lists-into-a-dictionary-in-python – Gillespie Feb 26 '15 at 19:59
  • 1
    Eww. You're*. I hate that typo -_- – Carcigenicate Feb 26 '15 at 20:35

2 Answers2

0

This is sudo code for how to do it, I actually don't know much python.

results = [];
for (i=0;i<artist_names.length();i++):         1
    if artist_names[i] == artist_choice:
        results.push(artist_songs[i])

but as @Carcigenicate said, there are better ways of going about this. If you are going to be making many searches on these lists you may want to first loop through and group the data into a hash table or what @Carcigenicate suggests.

@RPGillespie 's link explains how to combine them into a hash table, this is a much better way of searching.

rich green
  • 1,143
  • 4
  • 13
  • 31
0

Rich beat me to it, but I'll post a more pythonic example:

def getSongs(listOfArtists,listOfSongs,artistToLookup):
    songs = []
    for artist,song in zip(listOfArtists,listOfSongs):
        if (artist == artistToLookup):
            songs.append(song)
    return songs

Note using zip lets you iterate both lists at once fairly cleanly (without the need to subscript).

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117