Python同时从列表中推送和弹出
我有一个列表,当我不断地向它添加元素时,我想检查它是否为空,同时获取元素。通常,我们等待所有元素附加到列表中,然后从列表中获取元素并执行某些操作。在这种情况下,我们会浪费一些时间等待所有元素添加到列表中。要做到这一点,我需要掌握什么知识?多处理,多处理。虚拟,异步,抱歉,我还是新手,我想我最好向你解释一下为什么我要达到这种效果,这个问题来自一个网络爬虫Python同时从列表中推送和弹出,python,Python,我有一个列表,当我不断地向它添加元素时,我想检查它是否为空,同时获取元素。通常,我们等待所有元素附加到列表中,然后从列表中获取元素并执行某些操作。在这种情况下,我们会浪费一些时间等待所有元素添加到列表中。要做到这一点,我需要掌握什么知识?多处理,多处理。虚拟,异步,抱歉,我还是新手,我想我最好向你解释一下为什么我要达到这种效果,这个问题来自一个网络爬虫 import requests from model import Document def add_concrete_content
import requests
from model import Document
def add_concrete_content(input_list):
"""input_list data structure [{'url': 'xxx', 'title': 'xxx'}...]"""
for e in input_list:
r = requests.get(e['url'])
html = r.content
e['html'] = html
return input_list
def save(input_list):
for e in input_list:
Document.create(**e)
if __name__ == '__main__':
res = add_concrete_content(list)
save(res)
"""this is I normally do, I save data to mysql or whatever database,but
I think the drawback is I have to wait all the html add to dict and then
save to database, what if I have to deal with tons of data? Can I save
the dict with the html first? Can I save some time? A friend of mine
said this is a typical producer consumer problem, probably gonna use
at least two threads and lock, because without lock, data probably
gonna fall into disorder"""
你在含糊其辞。我认为你希望事情发生的方式有一种误解 您不需要任何额外的python rock science来做您想做的事情: 您只需执行以下操作即可检查列表是否为空:if list_uu:where list_uu是您的列表 您可以通过使用列表[idx]来验证任何元素,其中idx是元素的索引。例如,list_u[0]将获取列表的第一个元素,而list_[-1]将获取最后一个元素。 也就是说,如果需要在运行中处理这些元素,则不必等待所有元素都添加到列表中。您可能会寻找类似以下内容:
def push(list_):
count = 0
while True:
list_.append(count)
f()
count += 1
if count == 1000:
break
def f():
print('First element: {}'.format(list_[0]))
print('Last element: {}'.format(list_[-1]))
if __name__ == '__main__':
list_ = []
push(list_)
请直接在文章中包含代码,而不是截图。此外,您不必使用POP,因为它也会从列表中删除元素。在python中,您可以简单地使用list[index]语法。