遍历 python 中的并行列表
Looping over parallel lists in python
我正在阅读 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 关联的每首歌曲?如果用户输入逻辑输出应该是:
Underpressure
Ballin
Im the man
这是sudo代码,具体操作方法,其实我了解的不多python。
results = [];
for (i=0;i<artist_names.length();i++): 1
if artist_names[i] == artist_choice:
results.push(artist_songs[i])
但正如@Carcigenicate 所说,有更好的方法来解决这个问题。如果您要在这些列表上进行多次搜索,您可能需要首先循环并将数据分组到散列中 table 或@Carcigenicate 建议的内容。
@RPGillespie 的 link 解释了如何将它们组合成散列 table,这是一种更好的搜索方式。
Rich 先于我,但我会 post 一个更像 Python 的例子:
def getSongs(listOfArtists,listOfSongs,artistToLookup):
songs = []
for artist,song in zip(listOfArtists,listOfSongs):
if (artist == artistToLookup):
songs.append(song)
return songs
请注意,使用 zip
可以让您相当干净地同时迭代两个列表(无需下标)。
我正在阅读 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 关联的每首歌曲?如果用户输入逻辑输出应该是:
Underpressure
Ballin
Im the man
这是sudo代码,具体操作方法,其实我了解的不多python。
results = [];
for (i=0;i<artist_names.length();i++): 1
if artist_names[i] == artist_choice:
results.push(artist_songs[i])
但正如@Carcigenicate 所说,有更好的方法来解决这个问题。如果您要在这些列表上进行多次搜索,您可能需要首先循环并将数据分组到散列中 table 或@Carcigenicate 建议的内容。
@RPGillespie 的 link 解释了如何将它们组合成散列 table,这是一种更好的搜索方式。
Rich 先于我,但我会 post 一个更像 Python 的例子:
def getSongs(listOfArtists,listOfSongs,artistToLookup):
songs = []
for artist,song in zip(listOfArtists,listOfSongs):
if (artist == artistToLookup):
songs.append(song)
return songs
请注意,使用 zip
可以让您相当干净地同时迭代两个列表(无需下标)。