简体   繁体   中英

Python convert list of tuples into single tuple

Is there a way to convert a list of tuples into a single tuple? I have received a list of tuples from cursor.fetchall() but would like to make this into a single tuple:

curr_table_columns = cursor.fetchall()

For example:

[(u'w_id',), (u'w_name',), (u'w_street',)]

becomes

[(u'w_id', u'w_name', u'w_street')]

With itertools.chain , it's trivial. from itertools import chain and you can do either:

[tuple(chain.from_iterable(curr_table_columns))]

or:

[tuple(chain(*curr_table_columns))]

The former is preferred for long or unbounded iterable inputs (though don't wrap in tuple for unbounded!); for a small input (particularly one that's already a list or tuple ), the latter is slightly slower, but fine. Either one is going to be significantly faster than a genexpr and indexing for inputs of any size at all.

Try this:

a=[(u'w_id',), (u'w_name',), (u'w_street',)]

print [tuple([i[0] for i in a])]

Output:

[(u'w_id', u'w_name', u'w_street')]

Not efficient*, but it is simple:

>>> ts = [(u'w_id',), (u'w_name',), (u'w_street',)]
>>> sum(ts, ())
('w_id', 'w_name', 'w_street')

So, just wrap it in a list if you must:

>>> result = [sum(ts, ())]
>>> result
[('w_id', 'w_name', 'w_street')]

*Warning: scales quadratically. Some might be inclined to let is slide for joining some column names into a single container. Definitely don't try to process millions of tuples this way.

Use itertools solution for linear time.

This function can convert listWidgets item into single tuple and also convert multiple element of tuple into single element tuple : Used for Sqlite3 and data query from listwidgets.

def tuple_converter(self,item):
        target = ''
        for i in item:
            target += i + " " 
        target = target.rstrip()
        target = tuple(target.split(","))
        return target
#syntax  name = tuple_converter(tuple((item).split()))

'''

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM