Python MySQLDB:在列表中获取fetchall的结果 [英] Python MySQLDB: Get the result of fetchall in a list

查看:1735
本文介绍了Python MySQLDB:在列表中获取fetchall的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将fetchall操作的结果列在一个列表中,而不是元组或元组元组的元组。
例如,

  cursor = connection.cursor()#Cursor可以是普通游标或dict游标
query =从bs选择id
cursor.execute(query)
row = cursor.fetchall()

现在,问题是结果行是((123,),(234))或({'id':123},{'id':234})
我正在寻找的是(123,234)或[123,234]。我试图避免手动循环的项目。感谢提前

解决方案

列表推导怎么办?如果结果是((123,),(234,),(345,))

 >>> row = [item [0] for cursor.fetchall()] 
>>>>行
[123,234,345]

如果结果是 ({'id':123},{'id':234},{'id':345})

 >>> row = [item ['id'] for cursor.fetchall()] 
>>>>行
[123,234,345]


I would like to get the result of the fetchall operation in a list instead of tuple of tuple or tuple of dictionaries. For example,

cursor = connection.cursor() #Cursor could be a normal cursor or dict cursor
query = "Select id from bs"
cursor.execute(query)
row = cursor.fetchall()

Now, the problem is the resultant row is either ((123,),(234,)) or ({'id':123}, {'id':234}) What I am looking for is (123,234) or [123,234]. I am trying to avoid the manually looping over the items. Thanks in advance

解决方案

And what about list comprehensions? If result is ((123,), (234,), (345,)):

>>> row = [item[0] for item in cursor.fetchall()]
>>> row
[123, 234, 345]

If result is ({'id': 123}, {'id': 234}, {'id': 345}):

>>> row = [item['id'] for item in cursor.fetchall()]
>>> row
[123, 234, 345]

这篇关于Python MySQLDB:在列表中获取fetchall的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆