Loopin a comprehension of list

Question:

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?

Asked By: abh

||

Answers:

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)
Answered By: I_Hate_ReLU

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]]
Answered By: Edo Akse

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]
Answered By: chepner

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]]
Answered By: tobias_k
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.