【问题标题】:Creating a new list from list of dictionaries从字典列表创建一个新列表
【发布时间】:2019-11-29 22:07:45
【问题描述】:

背景

以下代码适用于将日期添加 2 天(例如,1/1/2000 变为 1/3/2000 并取自 Altering date in list of dictionary

import datetime

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'}]

for i in list_of_dic:           #Iterate list
    if i["type"] == 'DATE':     #Check 'type'
        i["text"] = (datetime.datetime.strptime(i["text"], "%m/%d/%Y") + datetime.timedelta(days=2)).strftime("%m/%d/%Y")   #Increment days. 

print(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': '01/03/2000'}, 
  {'id': 'T10', 'type': 'DOCTOR', 'start': 692, 'end': 701, 'text': 'Joe'}, 
 {'id': 'T11', 'type': 'DATE', 'start': 702, 'end': 710, 'text': '05/03/2000'}]

问题

如果想将print(list_of_dic) 的输出保存到一个名为new_list_of_dic 的新列表中,代码将如何更改?

【问题讨论】:

    标签: python-3.x string list dictionary text


    【解决方案1】:

    只需使用copy

    new_list_of_dic = list_of_dic.copy()
    

    或者如果你想要字符串?

    new_list_of_dic = str(list_of_dic)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2018-12-17
      • 2016-02-14
      • 2021-06-25
      相关资源
      最近更新 更多