Python——从字典的多个嵌套列表中删除字典



我想删除'qas'列表中所有的dict元素,当它的f1不是1.0时。

列表如下:

test_list = [
{'paragraphs': [{
'qas':[
{'q':'abc','id':'123','a':['4','d'],'f1':1.0},
{'q':'dsf','id':'343','a':['6','d'],'f1':0.5},
{'q':'wre','id':'565','a':['4','u'],'f1':0.2}
]}
]},

{'paragraphs': [{
'qas':[
{'q':'ujn','id':'874','a':['4','d'],'f1':1.0},
{'q':'yht','id':'454','a':['5','d'],'f1':0.7},
{'q':'nth','id':'676','a':['4','j'],'f1':0.4}
]}
]},
] 

我的预期结果是:

test_list = [

{'paragraphs': [{
'qas':[
{'q':'abc','id':'123','a':['4','d'],'f1':1.0}
]}
]},

{'paragraphs': [{
'qas':[
{'q':'ujn','id':'874','a':['4','d'],'f1':1.0}
]}
]},

]

我的当前代码:

for i in range(len(test_list)): 
for j in range(len(test_list[i]['paragraphs'][0]['qas'])):
if test_list[i]['paragraphs'][0]['qas'][j]['f1'] != 1:
del test_list[i]['paragraphs'][0]['qas'][j]

但是我得到一个索引错误:

1 for i in range(len(test_list)):
2     for j in range(len(test_list[i]['paragraphs'][0]['qas'])):
----> 3         if test_list[i]['paragraphs'][0]['qas'][j]['f1'] != 1:
4             del test_list[i]['paragraphs'][0]['qas'][j]
IndexError: list index out of range

有多层嵌套的列表和字典。我不知道如何解决这个问题。

iuc,这个可以完成任务。

for i in range(len(test_list)):
test_list[i]["paragraphs"][0]["qas"] = test_list[i]["paragraphs"][0]["qas"][:1]
print(test_list)

输出——

[{'paragraphs': [{'qas': [{'a': ['4', 'd'],
'f1': 1.0,
'id': '123',
'q': 'abc'}]}]},
{'paragraphs': [{'qas': [{'a': ['4', 'd'],
'f1': 1.0,
'id': '874',
'q': 'ujn'}]}]}]

试过了,效果不错,但我想学习更简单的方法来完成这个任务。

import itertools
tmp = []
for i in range(len(test_list)): 
for j in range(len(test_list[i]['paragraphs'][0]['qas'])):
if test_list[i]['paragraphs'][0]['qas'][j]['f1'] != 1:
tmp.append(False)
else:
tmp.append(True)        
test_list[i]['paragraphs'][0]['qas'] = list(itertools.compress(test_list[i]['paragraphs'][0]['qas'],tmp))

相关内容

  • 没有找到相关文章

最新更新