python - 将新项目添加到列表中?

标签 python list extend

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

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

相关文章:

python - 如何迭代 python 列表?

Python向Pandas Dataframe添加列,该列是另一列中列表元素的计数

c++ - 使用 c(++) 扩展时的 @staticmethod

class - 从 Typescript 中的声明接口(interface)扩展类

python - 扩展父类(super class),调用 Python 中的子类

python - 有没有办法更快地运行此 Python 代码段?

python - 按小时分组,同时考虑夏令时

python - 在 Python 中生成数据透视表 - Pandas? NumPy ? Xlrd?来自 csv

python - 嵌套Python字典

统计List的Size,有必要用free()吗?