在python中循环并行列表

时间:2015-02-26 19:41:00

标签: list for-loop python-3.2

我正在阅读itunes库文件。我抓住了艺术家的名字和歌曲,并将它们放在平行列表中,一个包含艺术家名字,另一个包含艺术家歌曲。我想通过仅使用列表

来做到这一点
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]

假设用户输入艺术家名称Logic,我将如何循环并行列表并打印出与艺术家Logic相关的每首歌曲?如果用户输入Logic,则输出应为:

Underpressure
Ballin
Im the man

2 个答案:

答案 0 :(得分:0)

这是sudo代码,如何做到这一点,我实际上不太了解python。

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

但正如@Carcigenicate所说,有更好的方法可以解决这个问题。如果您要对这些列表进行多次搜索,您可能需要首先遍历并将数据分组到哈希表或@Carcigenicate建议的内容。

@RPGillespie的链接解释了如何将它们组合成哈希表,这是一种更好的搜索方式。

答案 1 :(得分:0)

Rich打败了我,但我会发布一个更加pythonic的例子:

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

注意使用zip可以让你一次性干净地迭代这两个列表(不需要下标)。

相关问题