Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

type conversion - How to convert a two nested list of lists into a nested list of tuples in Python?

I am trying to convert a two nested list of lists into a nested list of tuples in Python. But I cant get the desired result. The input looks like:

first_list = [['best', 'show', 'ever', '!'],
              ['its', 'a', 'great', 'action','movie']]

second_list = [['O', 'B_A', 'O', 'O'],
               ['O', 'O', 'O', 'B_A','I_A']]

The desired output should look like:

result = [[('best','O'),('show','B_A'),('ever','O'),('!','O')],
          [('its','O'),('a','O'),('great','O'),('action','B_A'),('movie','I_A')]]

Thank you in advance!

question from:https://stackoverflow.com/questions/65838307/how-to-convert-a-two-nested-list-of-lists-into-a-nested-list-of-tuples-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
# zip both lists. You end up with pairs of lists
pl = zip(first_list, second_list)

# zip each pair of list and make list of tuples out of each pair of lists.
[[(e[0], e[1]) for e in zip(l[0], l[1])] for l in pl]

Note: not tested, done on mobile. But you got the idea.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...