[英]Store output of for loop into single variable
I have a for loop that retrieves bigram data of a page of text from an SQLite3 database. 我有一个for循环,可从SQLite3数据库中检索文本页面的bigram数据。
def bigram_db():
cursr.execute("SELECT * FROM trainedGrammar")
data = cursr.fetchall()
for data in data:
element = data
txt = element[0] #fetch first element of list
txt += txt
return txt
I tried using txt += txt but this only gives me a single paragraph worth bigram data when I tried to print cache outside the function bigram_db(). 我尝试使用txt + = txt,但是当我尝试在函数bigram_db()之外打印缓存时,这仅给了我一个有价值的bigram数据段落。 So how do I store all of the bigram data that is going to be output by the for loop, which can be accessed outside of the for loop and then when I print it, I want the entire bigram data of the database to be available.
因此,我该如何存储所有将由for循环输出的bigram数据,这些数据可以在for循环之外访问 ,然后在我打印时,希望数据库的整个bigram数据可用。
You don't need to execute fetchall()
, you can iterate directly on the cursor. 您不需要执行
fetchall()
,可以直接在游标上进行迭代。 And you cannot use the same variable txt
for two purposes; 而且,您不能将相同的
txt
变量用于两个目的。 in the loop, the line txt = element[0]
overwrites its old value. 在循环中,行
txt = element[0]
覆盖其旧值。
Your function should look like this: 您的函数应如下所示:
def bigram_db():
cursr.execute("SELECT * FROM trainedGrammar")
txt = ""
for row in cursr:
txt += row[0]
return txt
Or without a for loop: 或没有for循环:
def bigram_db():
cursr.execute("SELECT * FROM trainedGrammar")
return "".join([row[0] for row in cursr])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.