Reputation: 173
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']]
Upvotes: 0
Views: 1590
Reputation: 1520
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.
Upvotes: 0
Reputation: 155684
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 tuple
s:
>>> 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 tuple
s, 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.
Upvotes: 6
Reputation: 77407
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.
Upvotes: 0