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

时间:2021-03-25 00:32:56
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?

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

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

将它转换为['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!

我相信这不是最好的方法。请赐教!

6 个解决方案

#1


7  

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)

编辑您能评论成本权衡吗? (for loop和itertools)

Itertools is significantly faster:

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

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

编辑2你可以解释一下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.

请参阅拆包文件。

#2


4  

You could do

你可以做到

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

#3


2  

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

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

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'] ?

将它转换为['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

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

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

#4


2  

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

虽然IMO列表理解最具可读性

#5


1  

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']

#6


0  

Do a list comprehension like this:

做这样的列表理解:

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

#1


7  

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)

编辑您能评论成本权衡吗? (for loop和itertools)

Itertools is significantly faster:

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

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

编辑2你可以解释一下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.

请参阅拆包文件。

#2


4  

You could do

你可以做到

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

#3


2  

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

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

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'] ?

将它转换为['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

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

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

#4


2  

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

虽然IMO列表理解最具可读性

#5


1  

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']

#6


0  

Do a list comprehension like this:

做这样的列表理解:

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