2

I'm new to programming, and I need some help. I have a list like this

a=[[('the', 'b'), ('hotel', 'i')],[('the', 'b'), ('staff', 'i')]]

and I'm trying to get rid of the tuple while retaining the data in a list, the outcome should look like this

output=[['the', 'b', 'hotel', 'i'],['the', 'b', 'staff', 'i']]

Thank you so much

bb Yang
  • 51
  • 6
  • 1
    The keyword you're missing for your searches is "flatten", as in "how to flatten a list". – Prune Apr 17 '17 at 21:17

4 Answers4

1

You can do the following list comprehension:

>>> [[y for x in i for y in x] for i in a]
[['the', 'b', 'hotel', 'i'], ['the', 'b', 'staff', 'i']]

Note that this has nothing to do with tuples, which because of duck typing are treated the exact same way as lists in a list comprehension. You are essentially doing the operation described in Making a flat list out of list of lists in Python over multiple list items.

Community
  • 1
  • 1
brianpck
  • 8,084
  • 1
  • 22
  • 33
1

This can be accomplished via the sum function:

a=[[('the', 'b'), ('hotel', 'i')],[('the', 'b'), ('staff', 'i')]]
output = [sum(elem, ()) for elem in a]
print(output)

And if it must return a list:

a=[[('the', 'b'), ('hotel', 'i')],[('the', 'b'), ('staff', 'i')]]
output = [sum(map(list,elem), []) for elem in a]
print(output)
Neil
  • 14,063
  • 3
  • 30
  • 51
1

I guess you can use:

output = []
for x in a:
    output.append([element for tupl in x for element in tupl])

outputs:

[['the', 'b', 'hotel', 'i'], ['the', 'b', 'staff', 'i']]
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
1

Here is a "functional"-style variant of @nfn neil's A.

from itertools import repeat

list(map(list, map(sum, a, repeat(()))))
# -> [['the', 'b', 'hotel', 'i'], ['the', 'b', 'staff', 'i']]
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99