向列表中添加新项目?

2024-04-20 02:14:50 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题已经得到了解答,我知道如何将项目添加到列表中,但由于某些原因,它无法正常工作。你知道吗

因此,有一个.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

Tags: 文件项目列表ifcount原因数字sleep
1条回答
网友
1楼 · 发布于 2024-04-20 02:14:50

每次运行matchList = []行时,都会重置matchList。在问题代码中,这个初始化行似乎在while True:循环中,这意味着每次迭代都重置matchList,而不是通过.extend()函数建立它。这可以通过将该线移到循环外来解决:

matchList = []

while True:
    from time import sleep
    ...
    ...

相关问题 更多 >