在嵌套列表python中删除字符串的一部分

时间:2017-06-06 01:39:24

标签: python list python-3.x split nested

我试图在嵌套列表中只保留字符串的特定部分。我的代码如下:

answers = [
    ['person1', ' 2 1": ["answer 1"], "', ' 3 1": ["answer 0"], "', ...]
    ['person2', ' 2 1": ["answer 3"], "', ' 3 1": ["answer 1"], "', ...]]

我想删除部分字符串,以便剩下的唯一部分是:

answers = [
    ['person1', 'answer 1', 'answer 0', ...]
    ['person 2', 'answer 3', 'answer 1', ...]]

2 个答案:

答案 0 :(得分:1)

假设:

answers = [
    ['person1', ' 2 1": ["answer 1"], "', ' 3 1": ["answer 0"], "',],
    ['person2', ' 2 1": ["answer 3"], "', ' 3 1": ["answer 1"], "',]
]

您可以使用正则表达式来解析每个字符串以获得所需的模式p

import re


p = re.compile(r'(?!.*\[)(\w+\s*\d)')
new_answers = []
for lst in answers:
    new_answers.append([re.search(p, s).groups(0)[0] for s in lst])
new_answers
# [['person1', 'answer 1', 'answer 0'], ['person2', 'answer 3', 'answer 1']]

此特定pattern忽略第一个括号“[”后面的字符,并查找带有零个或多个空格和数字的字母。

答案 1 :(得分:0)

此代码有效:

answers = [
           ['person1', ' 2 1": ["answer 1"], "', ' 3 1": ["answer 0"], "'],
           ['person2', ' 2 1": ["answer 3"], "', ' 3 1": ["answer 1"], "']]

result = []
for person_ans in answers:
    list = []
    for val in person_ans:
        if "[" in val:
            temp = val.split("[")
            output = temp[1].split("]")[0]
            list.append(output)
        else:
            list.append(val)
    result.append(list)
print result

输出:

[['person1', '"answer 1"', '"answer 0"'], ['person2', '"answer 3"', '"answer 1"']]