首页 > 解决方案 > 如何从元组列表列表中删除项目,同时保留结构

问题描述

我有一个 2 元组列表的列表。它看起来像这样:

   data = [[[('hey', 9), ('how', 10), ('are', 7), ('you?', 21)], [('I', 0), ('am', 5), ('fine,', 8), ('and', 6), ('you?', 21)], [('I', 0), ('am', 5), ('fine,', 8), ('too.', 17)]], [[('My', 2), ('name', 13), ('is', 11), ('Jason,', 1), ("what's", 18), ('your', 22), ('name?', 14)], [('My', 2), ('name', 13), ('is', 11), ('Tina.', 4)], [('Nice', 3), ('to', 15), ('meet', 12), ('you.', 20)], [('Nice', 3), ('to', 15), ('meet', 12), ('you,', 19), ('too,', 16)]]]

如何按文本和整数拆分它,同时保留原始列表的结构?本质上,我想要:

text = [[['hey', 'how', 'are', 'you?'], ['I', 'am', 'fine,', 'and', 'you?'], ['I', 'am', 'fine,', 'too.']], [['My', 'name', 'is', 'Jason,', "what's", 'your', 'name?'], ['My', 'name', 'is', 'Tina.'], ['Nice', 'to', 'meet', 'you.'], ['Nice', 'to', 'meet', 'you,', 'too,']]]

ints = [[[9, 10, 7, 21], [0, 5, 8, 6, 21], [0, 5, 8, 17]], [[2, 13, 11, 1, 18, 22, 14], [2, 13, 11, 4], [3, 15, 12, 20], [3, 15, 12,19, 16]]]

标签: python

解决方案


你可以这样试试。

 data = [[[('hey', 9), ('how', 10), ('are', 7), ('you?', 21)], [('I', 0), ('am', 5), ('fine,', 8), ('and', 6), ('you?', 21)], [('I', 0), ('am', 5), ('fine,', 8), ('too.', 17)]], [[('My', 2), ('name', 13), ('is', 11), ('Jason,', 1), ("what's", 18), ('your', 22), ('name?', 14)], [('My', 2), ('name', 13), ('is', 11), ('Tina.', 4)], [('Nice', 3), ('to', 15), ('meet', 12), ('you.', 20)], [('Nice', 3), ('to', 15), ('meet', 12), ('you,', 19), ('too,', 16)]]]

text = []
inst = []

for p_data in data:
    x = []
    y = []
    for q_data in p_data:
        a = []
        b = []
        for tup in q_data:
            a.append(tup[0])
            b.append(tup[1])
        x.append(a)
        y.append(b)
    text.append(x)
    inst.append(y)
print(text)
print(inst)

推荐阅读