-1
mylist=[[('The','d'),('apple','n'),('is','v'),('red','a')],[('I','p'),('feel','v'),('fine','adv')]]

This is a list of lists of tuples, and I wish to create a new list of tuples with information from another list added to it accordingly.

new_list=[['b','i','o','o'],['o','o','o']]

for each sub_list of these two lists, I have the exact same number of items as illustrated, and I wish to add the first string of the first list in new_list to the first tuple of the first list in my_list, the second string of the first list in new_list to second tuple of first list in my_list, and so on.

The ideal output looks like this

output=[[('The','d','b'),('apple','n','i'),('is','v','o'),('red','a','o')],[('I','p','o'),('feel','v','o'),('fine','adv','o')]]

I'd appreciate any suggestions, thank you!!

bb Yang
  • 51
  • 6
  • 1
    Possible duplicate of [How to merge lists into a list of tuples in Python?](http://stackoverflow.com/questions/2407398/how-to-merge-lists-into-a-list-of-tuples-in-python) – Thomas Kühn May 19 '17 at 15:03

1 Answers1

0

Basically this question has been answered elsewhere, so I flagged the question as duplicate, but assuming that you are new to python, here is a solution to your problem.

output = [[(*t,c) for t,c in zip(l1,l2)] for l1,l2 in zip(mylist,new_list)]

The new output is created using a list nested list comprehension (creating a list of lists). To match corresponding items from two lists together, you can use zip, which returns a generator of tuples of these corresponding items. The for loop that iterates through these tuples unpacks them into two separate items, i.e.

for l1,l2 in zip(mylist,newlist)

groups the sublists of mylist and newlist together, which the for are then unpacked into the lists l1 and l2 during the for iteration. Finally, as the items of the sublists of my_list are tuples, I unpack these tuples 'on the fly' while generating the new tuple: (*t,c) is the same as (t[0],t[1],c). Please ask if anything stayed unclear.

Hope this helps.

Thomas Kühn
  • 9,412
  • 3
  • 47
  • 63