Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在嵌套列表python中删除字符串的一部分_Python_List_Python 3.x_Split_Nested - Fatal编程技术网

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

在嵌套列表python中删除字符串的一部分,python,list,python-3.x,split,nested,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',

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

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', ...]]
此代码适用于:

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"']]
鉴于:

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


此特定选项忽略第一个括号后面的字符[并查找包含零个或更多空格和数字的字母。

answers对象来自何处?可能重复的@AzatIbrakov answers来自导入的json数据是的,您是如何获得这种格式的列表的?可能在前面的步骤中使用类似json.loads的内容会有所帮助。请给出原始源的示例,以便我们可以查看如果不需要手动字符串解析就可以完成
answers = [
    ['person1', ' 2 1": ["answer 1"], "', ' 3 1": ["answer 0"], "',],
    ['person2', ' 2 1": ["answer 3"], "', ' 3 1": ["answer 1"], "',]
]
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']]