python - Index of each element within list of lists -
i have following list of lists:
>>> mylist=[['a','b','c'],['d','e'],['f','g','h']]
i want construct new list of lists each element tuple first value indicates index of item within sublist, , second value original value.
i can obtain using following code:
>>> final_list=[] >>> sublist in mylist: ... slist=[] ... i,element in enumerate(sublist): ... slist.append((i,element)) ... final_list.append(slist) ... >>> >>> final_list [[(0, 'a'), (1, 'b'), (2, 'c')], [(0, 'd'), (1, 'e')], [(0, 'f'), (1, 'g'), (2, 'h')]] >>>
is there better or more concise way using list comprehension?
final_list = [list(enumerate(l)) l in mylist]
Comments
Post a Comment