【问题标题】:How to convert a two nested list of lists into a nested list of tuples in Python?如何在 Python 中将两个嵌套的列表列表转换为嵌套的元组列表?
【发布时间】:2021-04-26 12:22:54
【问题描述】:

我正在尝试将 两个 嵌套列表列表转换为 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')]]

提前谢谢你!

【问题讨论】:

    标签: python type-conversion tuples nested-lists


    【解决方案1】:
    # 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]
    

    注意:未经测试,在移动设备上完成。但你明白了。

    【讨论】:

    • 它仍然缺少一个括号,这就是我在 e[1] 之后添加一个括号的原因,它现在可以工作了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多