Skip to main content
 首页 » 编程设计

python之从 sqlite 缓冲区中显示字符串的更多 pythonic 方式

2025年05月04日22del

我将 FB 帖子 ID 存储在 sqlite 表中。现在我想使用 post_id 查询 FB 图中的其他数据。下面的 hack 有效,但感觉很假......

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

y 的值现在类似于 96085205666_10153983162390667 并且可用于构建新的 FB api 调用,但必须有更 pythonic 的方式

请您参考如下方法:

根据您的要求,data_all 是 1 个元素的元组上的可迭代对象

`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])