【问题标题】:Adding a new item to a list?向列表中添加新项目?
【发布时间】:2020-04-06 08:06:16
【问题描述】:

这已得到解答,我知道如何将项目添加到列表中,但由于某种原因它无法正常工作。

因此,有一个包含 5000 首歌曲列表的 .dat 文件,每首歌曲都有分配给它们的随机数字。我已经预先分配了随机数,我必须运行一个循环,找到 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

【问题讨论】:

  • 因为你在循环内创建了列表?
  • SongAttributes 是什么类型的?
  • 就是这样。谢谢!

标签: python list extend


【解决方案1】:

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

matchList = []

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    • 2011-08-10
    • 1970-01-01
    • 2013-05-30
    • 2015-09-13
    相关资源
    最近更新 更多