首先,将您的文件读入一个列表。我假设您的文件格式是固定的:它包含
- 指定歌曲名称的一行
- 指定流派的行
- 指定艺术家的行
- 空行
- 重复
请注意,由于似乎没有标头,因此您不需要初始的header = afile.readline()
假设您将文件的所有行读入名为lines的列表中
lines = [line.strip() for line in afile]
# You could also do
# lines = afile.readlines()
# but that would leave behind trailing line breaks at the end of each line
现在你知道了
- 从第一行开始,每隔四行就是歌曲名称。因此,将
lines 列表分割为每四行,从第一行开始,并将其保存为名为@987654326@ 的列表
songs = lines[0::4]
genres = lines[1::4]
artists = lines[2::4]
现在,我们可以zip() 这些列表同时迭代它们,并打印与我们正在寻找的艺术家匹配的歌曲:
look_for_artist = "artist 2"
print(f"Songs by {look_for_artist}:")
for artist, genre, song in zip(artists, genres, songs):
if artist == look_for_artist:
print(song, genre)
# if you know that every artist has only one song, you can break the loop here since you found it already
# break
如果您是为一群艺术家这样做,我建议您先将数据读入字典(or a collections.defaultdict)。然后,您可以查找给定艺术家的字典值,这将比遍历列表快得多。
考虑到单个艺术家可以拥有多首歌曲的情况,我们将使用一个字典,其中键是艺术家的姓名,值是包含他们所有歌曲的列表。
import collections
lookup_dict = collections.defaultdict(list)
for artist, genre, song in zip(artists, genres, songs):
lookup_dict[artist].append((genre, song))
那么,你需要做的就是:
for genre, song in lookup_dict[look_for_artist]:
print(song, genre)
您可以不必将整个文件读入一个列表,然后通过以四行为一组逐行读取文件来将其处理成字典,但我将把它留给您作为练习。