Pregunta

I have the following list:

list = [(1,info1),(2,info2),(3,info3)...]

each info is consisted of a list of tuples

info1 = [(a1,b1,c1),(a1',b1',c1'),(a1",b1",c1")...]

for each element in list, i want to have the following:

otherlist = [(1,(a1,b1,c1)),(1,(a1',b1',c1')),(1,(a1",b1",c1"))...]

that is: the index in front of info to be placed in front of each tuple of info

I think this is doable, but I am not able to achieve this with simple list comprehension

Thanks for the help :)

¿Fue útil?

Solución 2

otherlist = [(x[0],y) for x in first_list for y in x[1]]

Otros consejos

Use a nested list comprehension:

otherlist = [[(L[0], t) for t in L[1]] for L in lst]

so for each element L in lst, we create a new list with tuples containing (L[0], elements of L[1]).

Demo:

>>> lst = [(1, [('a1', 'b1', 'c1'), ("a1'", "b1'", "c1'"), ('a1"', 'b1"', 'c1"')]), (2, [('a3', 'b3', 'c3'), ("a3'", "b3'", "c3'"), ('a3"', 'b3"', 'c3"')]), (3, [('a3', 'b3', 'c3'), ("a3'", "b3'", "c3'"), ('a3"', 'b3"', 'c3"')])]
>>> [[(L[0], t) for t in L[1]] for L in lst]
[[(1, ('a1', 'b1', 'c1')), (1, ("a1'", "b1'", "c1'")), (1, ('a1"', 'b1"', 'c1"'))], [(2, ('a3', 'b3', 'c3')), (2, ("a3'", "b3'", "c3'")), (2, ('a3"', 'b3"', 'c3"'))], [(3, ('a3', 'b3', 'c3')), (3, ("a3'", "b3'", "c3'")), (3, ('a3"', 'b3"', 'c3"'))]]
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top