简体   繁体   中英

Turn a list of single tuples into a list without tuples

I'm working with lists of single tuples that looks like this:

data = [[('jog',), ('Jim',), ('jell',), ('jig',)], [('jabs',), ('jilt',), ('job',), ('jet',)]]

Notice that the list contains two elements: two lists containing 4 tuples. Basically, I'm just trying to remove each tuple and make it look like this:

data = [['jog','Jim','jell','jig'], ['jabs','jilt','job','jet']]

I think this can probably be done with list comprehension, but I've tried for hours and can't come up with the magic formula. Can anyone help with this?

The listcomp "magic formula" you're looking for is best done with a nested listcomp using unpacking in the innermost listcomp:

data = [[x for [x] in sublist] for sublist in data]

The [x] there triggers the unpacking of the single element tuple in the most efficient manner possible (while also verifying it is in fact exactly one element per tuple , no more, no less). Otherwise it's a largely no-op nested listcomp.

Use list comprehension like so:

data = [[('jog',), ('Jim',), ('jell',), ('jig',)], [('jabs',), ('jilt',), ('job',), ('jet',)]]
data = [[tup[0] for tup in lst] for lst in data]
print(data)
# [['jog', 'Jim', 'jell', 'jig'], ['jabs', 'jilt', 'job', 'jet']]

If you want to flatten your tuples in a list, you can use itertools.chain :

import itertools

data = [[('jog',), ('Jim',), ('jell',), ('jig',)], [('jabs',), ('jilt',), ('job',), ('jet',)]]

result = [list(itertools.chain(*d)) for d in data]

# result = [['jog', 'Jim', 'jell', 'jig'], ['jabs', 'jilt', 'job', 'jet']]

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