Thi*_*ode 5 python tuples list cursor
query = 'select mydata from mytable'
cursor.execute(query)
myoutput = cursor.fetchall()
print myoutput
(('aa',), ('bb',), ('cc',))
Run Code Online (Sandbox Code Playgroud)
为什么它(cursor.fetchall)返回一个元组元组而不是一个元组,因为我的查询只询问一列数据?
将其转换为最佳方式是什么['aa', 'bb', 'cc']?
我可以这样做:
mylist = []
myoutput = list(myoutput)
for each in myoutput:
mylist.append(each[0])
Run Code Online (Sandbox Code Playgroud)
我相信这不是最好的方法.请赐教!
小智 7
这也有效:
>>> tu = (('aa',), ('bb',), ('cc',))
>>> import itertools
>>> list(itertools.chain(*tu))
['aa', 'bb', 'cc']
Run Code Online (Sandbox Code Playgroud)
编辑 Could you please comment on the cost tradeoff? (for loop and itertools)
Itertools明显更快:
>>> 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
Run Code Online (Sandbox Code Playgroud)
编辑2 Could you pl explain itertools.chain(*)
该*解包序列插入位置参数,在此情况下的元组的嵌套元组.
例:
>>> 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',)
Run Code Online (Sandbox Code Playgroud)
另一个例子:
>>> f('abcde')
len args: 1
abcde
>>> f(*'abcde')
len args: 5
a
b
c
d
e
Run Code Online (Sandbox Code Playgroud)
请参阅拆包文件.
| 归档时间: |
|
| 查看次数: |
2458 次 |
| 最近记录: |