访问嵌套列表内的字典


[[{'id': 1772391,
'prob': 0.8,
'label': 'PERSON',
'start_offset': 44,
'end_offset': 52,
'user': 15,
'document': 1062501},
{'id': 1772397,
'prob': 0.8,
'label': 'PERSON',
'start_offset': 150,
'end_offset': 169,
'user': 15,
'document': 1062501},
{'id': 1772405,
'prob': 0.8,
'label': 'PERSON',
'start_offset': 217,
'end_offset': 226,
'user': 15,
'document': 1062501},
{'id': 1772387,
'prob': 0.8,
'label': 'TITLE',
'start_offset': 0,
'end_offset': 21,
'user': 15,
'document': 1062501},
{'id': 1772389,
'prob': 0.8,
'label': 'TITLE',
'start_offset': 22,
'end_offset': 39,
'user': 15,
'document': 1062501},
{'id': 1772400,
'prob': 0.8,
'label': 'TITLE',
'start_offset': 189,
'end_offset': 203,
'user': 15,
'document': 1062501},
{'id': 1772403,
'prob': 0.8,
'label': 'TITLE',
'start_offset': 204,
'end_offset': 216,
'user': 15,
'document': 1062501},
{'id': 1772408,
'prob': 0.8,
'label': 'FACILITY',
'start_offset': 285,
'end_offset': 310,
'user': 15,
'document': 1062501},
{'id': 1772396,
'prob': 0.8,
'label': 'ORG',
'start_offset': 138,
'end_offset': 150,
'user': 15,
'document': 1062501},
{'id': 1772410,
'prob': 0.8,
'label': 'LOC',
'start_offset': 312,
'end_offset': 329,
'user': 15,
'document': 1062501}]]

list中唯一的一个list。我尝试访问列表中的start_offset和end_offset。如何访问它们?我试过这个代码:

[annotation[i][j]['end_offset'] for i,j in annotation]

p。S:注释是嵌套列表的名称

你的意思是:

>>> [{k: v for k, v in i.items() if k in ['start_offset', 'end_offset']} for x in annotation for i in x]
[{'start_offset': 44, 'end_offset': 52}, {'start_offset': 150, 'end_offset': 169}, {'start_offset': 217, 'end_offset': 226}, {'start_offset': 0, 'end_offset': 21}, {'start_offset': 22, 'end_offset': 39}, {'start_offset': 189, 'end_offset': 203}, {'start_offset': 204, 'end_offset': 216}, {'start_offset': 285, 'end_offset': 310}, {'start_offset': 138, 'end_offset': 150}, {'start_offset': 312, 'end_offset': 329}]
>>> 

试试这个代码-

lists = ([(i['start_offset'], i['end_offset']) for ele in annotation for i in ele])
start_offset = [i for i,j in lists]
end_offset= [j for i,j in lists]

结果:

print(start_offset)
[44, 150, 217, 0, 22, 189, 204, 285, 138, 312]
print(end_offset)
[52, 169, 226, 21, 39, 203, 216, 310, 150, 329]
# As a Single list
print(lists)
[(44, 52), (150, 169), (217, 226), (0, 21), (22, 39), (189, 203), (204, 216), (285, 310), (138, 150), (312, 329)]

即使你有一个以上的列表,这个也可以工作。

for end offset:

final_list=[]
for item in annotation:
for dict in item:
final_list.append(dict['end_offset'])
print(final_list)

输出:

[52, 169, 226, 21, 39, 203, 216, 310, 150, 329]

相关内容

  • 没有找到相关文章

最新更新