简体   繁体   English

向列表中添加新项目?

[英]Adding a new item to a list?

This has been answered and I know how to add items to a list, but for some reason it is not working correctly.这已得到回答,我知道如何将项目添加到列表中,但由于某种原因它无法正常工作。

So, there is a .dat file with a list of 5000 songs, each song has random numbers assigned to them.因此,有一个 .dat 文件,其中包含 5000 首歌曲,每首歌曲都分配有随机编号。 I have preassigned random numbers, and I have to run a loop that finds 10 or so songs with similar numbers and put those in a list.我已经预先分配了随机数,我必须运行一个循环,找到 10 首左右具有相似编号的歌曲并将它们放在一个列表中。 I set a maximum of 10 to the list.我在列表中设置了最多 10 个。

But when I use extend() it only adds the very last song that was scanned.但是当我使用 extend() 时,它只添加了扫描的最后一首歌曲。 I have no idea why its doing this.我不知道为什么这样做。

Here's the code:这是代码:

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

Every time the matchList = [] line is run, the matchList is reset.每次运行matchList = []行时, matchList都会重置。 In the question code, it looks like this initialization line is within the while True: loop, which means that every iteration resets the matchList instead of building upon it via the .extend() function.在问题代码中,这个初始化行看起来像是在while True:循环中,这意味着每次迭代都会重置matchList而不是通过.extend()函数构建它。 This can be solved by moving that line outside the loop:这可以通过将该行移到循环外来解决:

matchList = []

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM