如何转换元组的元组列在一行(pythonic)? [英] How do I convert tuple of tuples to list in one line (pythonic)?

查看:200
本文介绍了如何转换元组的元组列在一行(pythonic)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

query = 'select mydata from mytable'
cursor.execute(query)
myoutput = cursor.fetchall() 
print myoutput

(('aa',), ('bb',), ('cc',))


b $ b

为什么(cursor.fetchall)返回一个元组的元组而不是一个元组,因为我的查询只需要一列数据?

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?

将其转换为 ['aa','bb','cc']

我可以这样做:

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!

推荐答案

这也很好:

>>> tu = (('aa',), ('bb',), ('cc',))
>>> import itertools
>>> list(itertools.chain(*tu))
['aa', 'bb', 'cc']


b $ b

编辑 您能否评论成本折衷? (for循环和itertools)

Itertools显着更快:

Itertools is significantly faster:

>>> t = timeit.Timer(stmt="itertools.chain(*(('aa',), ('bb',), ('cc',)))")
>>> print t.timeit()
0.341422080994
>>> t = timeit.Timer(stmt="[a[0] for a in (('aa',), ('bb',), ('cc',))]")
>>> print t.timeit()
0.575773954391

编辑2 code>你可以解释itertools.chain(*)

Edit 2 Could you pl explain itertools.chain(*)

* 将序列解包成位置参数,在这种情况下是元组的嵌套元组。

That * unpacks the sequence into positional arguments, in this case a nested tuple of tuples.

示例:

>>> def f(*args):
...    print "len args:",len(args)
...    for a in args:
...       print a
... 
>>> tu = (('aa',), ('bb',), ('cc',))
>>> f(tu)
len args: 1
(('aa',), ('bb',), ('cc',))
>>> f(*tu)
len args: 3
('aa',)
('bb',)
('cc',)

另一个例子:

>>> f('abcde')
len args: 1
abcde
>>> f(*'abcde')
len args: 5
a
b
c
d
e

请参阅文档开箱

这篇关于如何转换元组的元组列在一行(pythonic)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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