如何将元组的元组转换为一行列表(pythonic)?
query = 'select mydata from mytable'
cursor.execute(query)
myoutput = cursor.fetchall()
print myoutput
(('aa',), ('bb',), ('cc',))
既然我的查询只要求一列数据,为什么它(cursor.fetchall)返回一个元组而不是一个元组?
将其转换为 ['aa', 'bb', 'cc']
的最佳方法是什么?
我可以做这样的事情:
mylist = []
myoutput = list(myoutput)
for each in myoutput:
mylist.append(each[0])
我确信这不是最好的方法。请赐教!
query = 'select mydata from mytable'
cursor.execute(query)
myoutput = cursor.fetchall()
print myoutput
(('aa',), ('bb',), ('cc',))
Why is it (cursor.fetchall) returning a tuple of tuples instead of a tuple since my query is asking for only one column of data?
What is the best way of converting it to ['aa', 'bb', 'cc']
?
I can do something like this :
mylist = []
myoutput = list(myoutput)
for each in myoutput:
mylist.append(each[0])
I am sure this isn't the best way of doing it. Please enlighten me!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这也有效:
编辑
您能否对成本权衡发表评论? (for 循环和 itertools)
Itertools 明显更快:
编辑 2
你能解释一下 itertools.chain(*)
那个
*
将序列解包为位置参数,在本例中为元组的嵌套元组。示例:
又一个示例:
参见解包文档。
This works as well:
Edit
Could you please comment on the cost tradeoff? (for loop and itertools)
Itertools is significantly faster:
Edit 2
Could you pl explain itertools.chain(*)
That
*
unpacks the sequence into positional arguments, in this case a nested tuple of tuples.Example:
Another example:
See the documents on unpacking.
你可以做
You could do
外元组是完整的结果;每个内部元组代表该结果中的一条记录;因为您只要求一个字段,所以每个内部元组只有一个元素。
有多种方法,哪种方法“最好”取决于您在做什么...
简单的列表理解:
简单的生成器(节省内存使用):
如果您只需要处理
myoutput
中的项目,你也可以这样做如果你已经分析了你的代码并发现这是一个瓶颈,那么你可以选择可读性较低但速度更快的代码:
或者,如果你只需要处理它:
The outer tuple is the complete result; each inner tuple represents one record in that result; because you asked for only one field, each inner tuple has only one element.
There are several ways, and which is 'best' depends on what you are doing...
Simple list comprehension:
Simple generator (saves on memory usage):
If you just need to process the items in
myoutput
, you could also doIf you have profiled your code and discovered that this is a bottleneck, then you can go for less readable but faster:
or, again if you just need to process it:
您所做的事情是正确的,但更简洁,并且性能可能会更好,
或者如果您讨厌
for
关键字,您可以使用 map,这是另一种方式,
尽管 IMO 列表理解最具可读性
What you are doing is correct but more concise and may be better performing could be
or if you hate
for
keyword, you can use mapand here is another way
though IMO list comprehension is most readable
这有效:
说明:
你也可以这样做:
This works:
Explanation:
You could also do:
像这样进行列表理解:
Do a list comprehension like this: