从sqlite bu中发现字符串的更具pythonic的方式

2024-09-22 14:37:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我将FB post id存储在一个sqlite表中。现在我想使用post_id查询FB图中的其他数据。下面的黑客作品,但它感觉很hokey。。。你知道吗

cur.execute("SELECT post_id FROM fbposts") 
data_all = cur.fetchall()
for x in data_all:
    y = "%s" % x

y的值现在类似于96085205666_10153983162390667,可以用来构造一个新的fbapi调用,但必须有一种更为python的方法


Tags: 数据fromidexecutesqlitedatafball
2条回答

使用以下模式如何:

cur.execute("SELECT post_id FROM fbposts") 
data_all = [item[0] for item in cur.fetchall()]

现在您的数据将是您想要的字符串列表。如果您想为每个post\u id打电话,现在可以执行以下操作:

for post_id in data_all:
    fb.call(post_id)

对于您的请求,data_all是1个元素的元组上的iterable

`y = "%s" % x` properly converts a 1-element tuple to a string, but you're right, it's not the best way.

fetchall(): Fetches all (remaining) rows of a query result, returning a list. Note that the cursor’s arraysize attribute can affect the performance of this operation. An empty list is returned when no rows are available.

要获取此元素并创建包含字符串的列表,请执行以下操作:

[x for (x,) in data_all]

这将解压元组中的x,并创建一个字符串列表(相当于[x[0] for x in data_all]

相关问题 更多 >