python:在数据结构中查找匹配项
我的数据结构如下表所示:python:在数据结构中查找匹配项,python,Python,我的数据结构如下表所示: Song = namedtuple('Song', ['fullpath', 'tags']) # tags is a dictionary Album = namedtuple('Album', ['album_key', 'songs']) The data_structure is a list of Albums 有数千张专辑,每张都有10-20首歌曲 我正在寻找匹配项: for new_album in new_albums: for old_a
Song = namedtuple('Song', ['fullpath', 'tags']) # tags is a dictionary
Album = namedtuple('Album', ['album_key', 'songs'])
The data_structure is a list of Albums
有数千张专辑,每张都有10-20首歌曲
我正在寻找匹配项:
for new_album in new_albums:
for old_album in old_albums:
if new_album.album_key == old_album.album_key:
for new_song in new_album.songs:
for old_song in old_album.songs:
if new_song.fullpath == old_song.fullpath:
# do something
break
这是低效的,主要是因为它会为每个新专辑重新启动通过旧专辑的循环。一种解决方案是使用字典,但我需要排序和排序。ICT只按键插入排序。另一种方法是将列表更改为字典、进程,然后再更改回列表,但这似乎并不理想
有更好的方法吗?您不必将数据转换为新格式,但仍可以使用dict查找匹配项:
paths = {}
for album, a_id in zip(albums, xrange(len(albums))):
for song, s_id in zip(album.songs, xrange(len(album.songs))):
if song.fullpath not in paths:
paths[song.fullpath] = (a_id, s_id)
else:
# do something
break
当你到达#做点什么
时,你可以使用路径[song.fullpath]
为你提供[0]
(相册)和[1]
匹配的歌曲。因此:
matched_album, matched_song = paths[song.fullpath]
print albums[matched_album].songs[matched_song], "matches!"
这有帮助吗?相册键是否唯一,或者是否存在具有相同的相册键的不同相册?是否可以对相册进行排序?相册键是否唯一。专辑列表是可排序的。无论是哪一张专辑,只要找到具有相同完整路径的任意两首歌曲就足够了吗?确实需要对列表进行排序吗?通常,这样做的原因是允许二进制搜索,但使用字典,按键搜索已经很快了(er)
sorted(new_albums)
将在您实际需要时为您提供相册键的排序列表。顺便说一句,对于zip中的i,ix(foo,xrange(len(foo)):与枚举(foo)中的ix,i的相同: