这个问题已经得到解答,我知道如何将项目添加到列表中,但由于某种原因它无法正常工作。
因此,有一个 .dat 文件,其中包含 5000 首歌曲的列表,每首歌曲都分配有随机编号。我已经预先分配了随机数,并且必须运行一个循环来查找 10 首左右具有相似数字的歌曲,并将它们放入列表中。我为列表设置了最多 10 个。
但是当我使用extend()时,它只添加最后扫描的歌曲。我不知道为什么要这样做。
代码如下:
while True:
from time import sleep
matchList = []
SongAttributes = myMusic.getSongAttributes(num)
print(SongAttributes)
num += 1
sleep(0)
if set(likedAttributes) & set(SongAttributes):
matchList.extend(SongAttributes)
count += 1
if count > 10:
print('List:')
print(matchList)
break
最佳答案
每次运行 matchList = []
行时,matchList
都会重置。在问题代码中,看起来此初始化行位于 while True:
循环内,这意味着每次迭代都会重置 matchList
,而不是通过 在其基础上构建>.extend()
函数。这可以通过将该行移到循环之外来解决:
matchList = []
while True:
from time import sleep
...
...
关于python - 将新项目添加到列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59312935/