0

I have this form of a list of lists:

[[('1st',), ('2nd',), ('5th',)], [('1st',)]]

I want to convert this to:

[['1st', '2nd', '5th'], ['1st']]

I tried this:

res = [list(ele) for ele in racer_placement for ele in ele]

But the result I got:

[['1st'], ['2nd'], ['5th'], ['1st']]
Georgy
  • 12,464
  • 7
  • 65
  • 73
elnino
  • 173
  • 2
  • 9
  • Does this answer your question? [Convert tuple to list and back](https://stackoverflow.com/questions/16296643/convert-tuple-to-list-and-back) – Ahmad Ismail Aug 25 '20 at 23:27

3 Answers3

6

You need nested comprehensions (with either a two layer loop in the inner comprehension, or use chain.from_iterable for flattening). Example with two layer loop (avoids need for imports), see the linked question for other ways to flatten the inner list of tuples:

>>> listolists = [[('1st',), ('2nd',), ('5th',)], [('1st',)]]
>>> [[x for tup in lst for x in tup] for lst in listolists]
[['1st', '2nd', '5th'], ['1st']]

Note that in this specific case of single element tuples, you can avoid the more complicated flattening with just:

 >>> [[x for x, in lst] for lst in listolists]

per the safest way of getting the only element from a single-element sequence in Python.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
0

You can use slicing to replace the contents of the first level of lists with a new list built from the first element of the tuples.

>>> racer_placement = [[('1st',), ('2nd',), ('5th',)], [('1st',)]]
>>> for elem in racer_placement:
...     elem[:] = [elem2[0] for elem2 in elem]
... 
>>> racer_placement
[['1st', '2nd', '5th'], ['1st']]

Since this is updating the inner list, any other reference to those lists would also see the change. That could be great or disasterous.

tdelaney
  • 73,364
  • 6
  • 83
  • 116
0
List = [[('1st',), ('2nd',), ('5th',)], [('1st',)]]
Parentlist = [] 
Temp=[] 
for childlist in List:
     Temp=[] 
     for x in childlist
          Temp.Add(x[0]) 
     parentlist.Add(Temp) 

This is untested.

Qudus
  • 1,440
  • 2
  • 13
  • 22