当我使用这个脚本来获取数组A中的每个元素在数组B中重复的次数时,我得到了正确的结果
A = ['text1','text2','text3','text4']
B = ['text1','text2','text3','text4','text1','text2','text3','text4','text1','text2','text3','text4','text1','text2','text3','text4','text1','text2','text3','text4','text3','text4']
for c in A :
countVar = 0
for e in B :
if c == e :
countVar +=1
print c
print countVar但是,当B数组在本例中是从SQL查询返回时,is确实为第一个元素拉出了正确的数字,在本例中,第一个元素是text1,而对于其他元素计数,它拉出0。
cursor = db.cursor()
cursor.execute("select * from Table")
A = ['text1','text2','text3','text4']
for element in A:
#print element
for row in cursor.fetchall() :
if row[0] == element :
#Count
countClient += 1
print row
print countClient
countClient = 0结果如下:知道我的表中有text2和text3
text1
15
text2
0
text3
0
text4
0
有人知道为什么会这样吗?或者提出了另一种方法来做到这一点?我还在做其他的计算,比如计算从SQL数组返回的值的总和,以及AVG,因为我正在做一些数据处理。
提前感谢!
发布于 2013-03-06 11:15:03
我对documentation的理解是,fetchall()在第一次循环后不会返回任何内容。为了进行调试,您应该检查它在第二次(以及以后)传递时是否真的进入了内部for循环。
要解决这个问题,只需对代码进行少量修改,我可以考虑以下几个选项:
fetchall循环,将其存储在一个新的数组中,并在当前代码中使用它。execute。抱歉,我不能给出更多细节,但Python不是我所熟悉的语言。
--
对于第一种选择,类似于(伪代码):
i = 0
C = []
for row in cursor.fetchall() :
c[i] = row[0]
i += 1然后在你的内循环中,用for row in cursor.fetchall()代替for el in C
https://stackoverflow.com/questions/15238229
复制相似问题