如何将元组的元组转换为一行列表(pythonic)?

发布于 2024-12-16 17:45:39 字数 427 浏览 1 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

°如果伤别离去 2024-12-23 17:45:39

这也有效:

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

编辑 您能否对成本权衡发表评论? (for 循环和 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

编辑 2 你能解释一下 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',)

又一个示例:

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

参见解包文档

This works as well:

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

Edit Could you please comment on the cost tradeoff? (for loop and 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

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

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

Example:

>>> 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',)

Another example:

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

See the documents on unpacking.

花落人断肠 2024-12-23 17:45:39

你可以做

>>> tup = (('aa',), ('bb',), ('cc',))
>>> lst = [a[0] for a in tup]
>>> lst
['aa', 'bb', 'cc']

You could do

>>> tup = (('aa',), ('bb',), ('cc',))
>>> lst = [a[0] for a in tup]
>>> lst
['aa', 'bb', 'cc']
妞丶爷亲个 2024-12-23 17:45:39

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

外元组是完整的结果;每个内部元组代表该结果中的一条记录;因为您只要求一个字段,所以每个内部元组只有一个元素。

将其转换为 ['aa', 'bb', 'cc'] 的最佳方法是什么?

有多种方法,哪种方法“最好”取决于您在做什么...

简单的列表理解:

mylist = [each[0] for each in myoutput]

简单的生成器(节省内存使用):

mygen = (each[0] for each in myoutput)
for result in mygen:
    print result

如果您只需要处理 myoutput 中的项目,你也可以这样做

for each, in myoutput:
    print each

如果你已经分析了你的代码并发现这是一个瓶颈,那么你可以选择可读性较低但速度更快的代码:

import itertools
mylist = list(itertools.chain(*myoutput))

或者,如果你只需要处理它:

import itertools
for result in itertools.chain(*myoutput):
    print result

Why is cursor.fetchall() returning a tuple of tuples instead of a tuple since my query is asking for only one column of data?

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.

What is the best way of converting it to ['aa', 'bb', 'cc'] ?

There are several ways, and which is 'best' depends on what you are doing...

Simple list comprehension:

mylist = [each[0] for each in myoutput]

Simple generator (saves on memory usage):

mygen = (each[0] for each in myoutput)
for result in mygen:
    print result

If you just need to process the items in myoutput, you could also do

for each, in myoutput:
    print each

If you have profiled your code and discovered that this is a bottleneck, then you can go for less readable but faster:

import itertools
mylist = list(itertools.chain(*myoutput))

or, again if you just need to process it:

import itertools
for result in itertools.chain(*myoutput):
    print result
北恋 2024-12-23 17:45:39

您所做的事情是正确的,但更简洁,并且性能可能会更好,

>>> [item for item, in (('aa',), ('bb',), ('cc',)) ]
['aa', 'bb', 'cc']

或者如果您讨厌 for 关键字,您可以使用 map

>>> map(lambda a:a[0], (('aa',), ('bb',), ('cc',)) )
['aa', 'bb', 'cc']

,这是另一种方式,

>>> reduce(lambda a, b:a+b, (('aa',), ('bb',), ('cc',)) )
('aa', 'bb', 'cc')

尽管 IMO 列表理解最具可读性

What you are doing is correct but more concise and may be better performing could be

>>> [item for item, in (('aa',), ('bb',), ('cc',)) ]
['aa', 'bb', 'cc']

or if you hate for keyword, you can use map

>>> map(lambda a:a[0], (('aa',), ('bb',), ('cc',)) )
['aa', 'bb', 'cc']

and here is another way

>>> reduce(lambda a, b:a+b, (('aa',), ('bb',), ('cc',)) )
('aa', 'bb', 'cc')

though IMO list comprehension is most readable

梦罢 2024-12-23 17:45:39

这有效:

>>> tups=(('aa',), ('bb',), ('cc',))
>>> list(*(zip(*tups)))
['aa', 'bb', 'cc']

说明:

1) *tups unpacks the nested tuples  ('aa'),('bb'),('cc')
2) zip produces a list of a single tuple with all the elements: [('aa','bb','cc')]
3) * unpacks that  into  'aa', 'bb', 'cc'
4) creates a list from that unpacking.

你也可以这样做:

>>> list(zip(*tups)[0])
['aa', 'bb', 'cc']

This works:

>>> tups=(('aa',), ('bb',), ('cc',))
>>> list(*(zip(*tups)))
['aa', 'bb', 'cc']

Explanation:

1) *tups unpacks the nested tuples  ('aa'),('bb'),('cc')
2) zip produces a list of a single tuple with all the elements: [('aa','bb','cc')]
3) * unpacks that  into  'aa', 'bb', 'cc'
4) creates a list from that unpacking.

You could also do:

>>> list(zip(*tups)[0])
['aa', 'bb', 'cc']
无敌元气妹 2024-12-23 17:45:39

像这样进行列表理解:

mylist = [ x[0] for x in myoutput ]

Do a list comprehension like this:

mylist = [ x[0] for x in myoutput ]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文