簡體   English   中英

遍歷字典列表

[英]Looping through list of dictionary

背景

我有一個字典列表,如下所示:

list_of_dic = [{'id': 'T1','type': 'LOCATION-OTHER','start': 142,'end': 148,'text': 'California'},
 {'id': 'T2', 'type': 'PHONE', 'start': 342, 'end': 352, 'text': '123456789'},
 {'id': 'T3', 'type': 'DATE', 'start': 679, 'end': 687, 'text': '1/1/2000'},
 {'id': 'T10','type': 'DOCTOR','start': 692,'end': 701,'text': 'Joe'},
 {'id': 'T11', 'type': 'DATE', 'start': 702, 'end': 710, 'text': '5/1/2000'}]

目標

使用if語句或for語句print'type': 'DATE以外的所有內容'type': 'DATE

我希望它看起來像這樣:

for dic in list_of_dic: 

    #skip  'DATE' and corresponding 'text'
    if edit["type"] == 'DATE':
        edit["text"] = skip this

    else:
        print everything else that is not 'type':'DATE' and corresponding 'text': '1/1/2000'

期望的輸出

list_of_dic = [{'id': 'T1','type': 'LOCATION-OTHER','start': 142,'end': 148,'text': 'California'},
     {'id': 'T2', 'type': 'PHONE', 'start': 342, 'end': 352, 'text': '123456789'},
     {'id': 'T10','type': 'DOCTOR','start': 692,'end': 701,'text': 'Joe'}]

如何使用循環實現所需的輸出?

嘗試這個:

list_of_dic = [{'id': 'T1','type': 'LOCATION-OTHER','start': 142,'end': 148,'text': 'California'},
 {'id': 'T2', 'type': 'PHONE', 'start': 342, 'end': 352, 'text': '123456789'},
 {'id': 'T3', 'type': 'DATE', 'start': 679, 'end': 687, 'text': '1/1/2000'},
 {'id': 'T10','type': 'DOCTOR','start': 692,'end': 701,'text': 'Joe'},
 {'id': 'T11', 'type': 'DATE', 'start': 702, 'end': 710, 'text': '5/1/2000'}]

newList = []
for dictionary in list_of_dic:
    if dictionary['type'] != 'DATE':
        newList.append(dictionary)

使用清單理解:

In [1]: list_of_dic = [{'id': 'T1','type': 'LOCATION-OTHER','start': 142,'end': 148,'text'
   ...: : 'California'},
   ...:  {'id': 'T2', 'type': 'PHONE', 'start': 342, 'end': 352, 'text': '123456789'},
   ...:  {'id': 'T3', 'type': 'DATE', 'start': 679, 'end': 687, 'text': '1/1/2000'},
   ...:  {'id': 'T10','type': 'DOCTOR','start': 692,'end': 701,'text': 'Joe'},
   ...:  {'id': 'T11', 'type': 'DATE', 'start': 702, 'end': 710, 'text': '5/1/2000'}]

In [2]: out = [i for i in list_of_dic if i['type'] != 'DATE']

In [3]: out
Out[3]:
[{'id': 'T1',
  'type': 'LOCATION-OTHER',
  'start': 142,
  'end': 148,
  'text': 'California'},
 {'id': 'T2', 'type': 'PHONE', 'start': 342, 'end': 352, 'text': '123456789'},
 {'id': 'T10', 'type': 'DOCTOR', 'start': 692, 'end': 701, 'text': 'Joe'}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM