Python - deq 函数打印 8 次 - 防止只打印一次?

Python - deq function prints out 8 times - prevent to print only once?

所以我对 deq 进行了一些尝试,快要完成了,但是由于 deq 的长度,我担心它打印了 8 次,而我只想打印一次。

我所做的是:

old_list = []
deq = deque(old_list, maxlen=8)
url = 'https://www.supremecommunity.com/restocks/eu/'

while True:
    try:
        new_list = []

        bs4 = soup(requests.get(url).text, "html.parser")

        for item in bs4.findAll('div', {'class': 'restock-item'}):
            if item.find('div', {'class': 'user-detail'}):
                name = item.find('h5', {'class': 'handle restock-name'}).string
                color = item.find('h6', {'class': 'restock-colorway'}).string

                new_list.append(name + color)

        for newitem in new_list:
            if newitem not in deq:
                print(name)
                print(color)
                deq.append(newitem)

            else:
                print('Sleeping 5 sec')
                time.sleep(5)
    except:
        continue 

基本上它会检查网站并打印出 name 和 color 然后将其添加到 deq 列表中。但是,由于 maxlen=8 和我的 question 是:

,我的输出打印了 8 次相同的名称和颜色

我怎样才能让它只打印一次?

您总是打印相同的变量 namecolor,因为它们在上面的 for 循环中最后定义。

      name = item.find('h5', {'class': 'handle restock-name'}).string
      color = item.find('h6', {'class': 'restock-colorway'}).string

当您在第二个 for 循环中打印 print(name)print(color) 时,它始终指的是 namecolor 具有的最后一个值.

要解决这个问题,您应该在打印语句中引用变量 newitem

编辑:

这里只是连接两个字符串。

new_list.append(name + color)

我建议你把它做成列表的列表。

new_list.append([name,color])

然后您可以使用 print(newitem[0])print(newitem[1]) 打印不同的名称和颜色。