所以目前我有一个for循环,它会导致python程序死掉,程序会说'Killed‘。它在大约6000个条目中变慢,程序在大约6852个列表项中慢慢消亡。我该如何解决这个问题?
我想这是因为列表太大了。
我试着在6000左右将列表一分为二。也许是因为内存管理之类的原因。如果能帮上忙,我们将不胜感激。
for id in listofids:
connection = psycopg2.connect(user = "username", password = "password", host = "localhost", port = "5432", database = "darkwebscraper")
cursor = connection.cursor()
cursor.execute("select darkweb.site_id, darkweb.site_title, darkweb.sitetext from darkweb where darkweb.online='true' AND darkweb.site_id = %s", ([id]))
print(len(listoftexts))
try:
row = cursor.fetchone()
except:
print("failed to fetch one")
try:
listoftexts.append(row[2])
cursor.close()
connection.close()
except:
print("failed to print")发布于 2019-06-23 05:59:50
您是对的,这可能是因为列表变得很大: python列表是内存中连续的空格。每次添加到列表中时,python都会查看下一个位置是否有点,如果没有,它会将整个数组重新定位到有足够空间的地方。你的数组越大,python需要重新定位的就越多。
一种方法是预先创建一个大小合适的数组。
编辑:为了清楚起见,我举了一个例子来说明我的观点。我做了两个函数。第一个在每次迭代时将字符串化的索引(使其更大)附加到一个列表中,另一个只填充一个numpy数组:
import numpy as np
import matplotlib.pyplot as plt
from time import time
def test_bigList(N):
L = []
times = np.zeros(N,dtype=np.float32)
for i in range(N):
t0 = time()
L.append(str(i))
times[i] = time()-t0
return times
def test_bigList_numpy(N):
L = np.empty(N,dtype="<U32")
times = np.zeros(N,dtype=np.float32)
for i in range(N):
t0 = time()
L[i] = str(i)
times[i] = time()-t0
return times
N = int(1e7)
res1 = test_bigList(N)
res2 = test_bigList_numpy(N)
plt.plot(res1,label="list")
plt.plot(res2,label="numpy array")
plt.xlabel("Iteration")
plt.ylabel("Running time")
plt.legend()
plt.title("Evolution of iteration time with the size of an array")
plt.show()我得到了以下结果:

您可以在图中看到,对于列表情况,您经常会有一些峰值(可能是由于重新定位),并且它们似乎随着列表的大小而增加。本例使用了较短的附加字符串,但是字符串越大,您就会看到越多的效果。
如果它不能做到这一点,那么它可能会链接到数据库本身,但如果不知道数据库的细节,我就无法帮助您。
https://stackoverflow.com/questions/56719455
复制相似问题