首页 > 解决方案 > 如何在 Python 中将两个嵌套的列表列表转换为嵌套的元组列表?

问题描述

我正在尝试将两个嵌套的列表列表转换为 Python 中的嵌套元组列表。但我无法得到想要的结果。输入看起来像:

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

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

所需的输出应如下所示:

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

先感谢您!

标签: pythontype-conversiontuplesnested-lists

解决方案


# 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]

注意:未经测试,在手机上完成。但你明白了。


推荐阅读