Reputation: 51
I have a list:
lst = [[['X', 'A'], 1, 2, 3], [['Y', 'B'], 1, 2, 3], [['Z', 'C'], 1, 2, 3]]
And i want to turn it into:
new_lst = [['X', 1, 2, 3], ['A', 1, 2, 3] ['Y', 1, 2, 3], ['B', 1, 2, 3], ['Z', 1, 2, 3], ['C', 1, 2, 3]]
I've got it to work with a a single one of them with comprehension.
lst2 = [['X', 'Y'], 1, 2, 3]
fst, *rest = lst2
new_lst3= [[i, *rest] for i in fst]
Which gives me new_list3 = [['X', 1, 2, 3], ['Y', 1, 2, 3]]
But I don't know how to loop to make it work on the full list.
Any good solutions?
Upvotes: 0
Views: 60
Reputation: 82899
You can turn your list comprehension for a single element into a nested list comprehension for the entire list:
>>> lst = [[['X', 'A'], 1, 2, 3], [['Y', 'B'], 1, 2, 3], [['Z', 'C'], 1, 2, 3]]
>>> [[i, *rest] for (fst, *rest) in lst for i in fst]
[['X', 1, 2, 3], ['A', 1, 2, 3], ['Y', 1, 2, 3], ['B', 1, 2, 3], ['Z', 1, 2, 3], ['C', 1, 2, 3]]
Upvotes: 2
Reputation: 531205
You can unpack each sublist into the list of letters and the "rest", then iterate over the letters to build new sublists from a letter and the rest.
new_lst = [[c, *rest] for letters, *rest in lst for c in letters]
Upvotes: 3
Reputation: 4391
You're only missing the loop to iterate through the lst
from pprint import pprint
lst = [[['X', 'A'], 1, 2, 3], [['Y', 'B'], 4, 5, 6], [['Z', 'C'], 7, 8, 9]]
new_lst = []
for elem in lst:
fst, *rest = elem
new_lst.extend([[i, *rest] for i in fst])
pprint(new_lst, indent=4)
output
[ ['X', 1, 2, 3],
['A', 1, 2, 3],
['Y', 4, 5, 6],
['B', 4, 5, 6],
['Z', 7, 8, 9],
['C', 7, 8, 9]]
Upvotes: 2
Reputation: 13
You could just replace the first term right with the first letter right?
lst = [[['X', 'A'], 1, 2, 3], [['Y', 'B'], 1, 2, 3], [['Z', 'C'], 1, 2, 3]]
for item in lst:
item[0] = item[0][0];
print(lst)
Upvotes: -1