我正在尝试根据Python reclaiming memory after deleting items in a dictionary 从字典中删除键。后者提出的一个解决办法是:
to create a new dictionary by copying the old dictionary
在源代码1中,我做了以下操作:
new_flights
del flights[key]
new_flights = copy.deepcopy(flights)
在源代码2中,我做了以下操作:
new_flights
new_flights[key] = flights[key]
flights.clear()
两种方法都不起作用。内存没有被释放。你知道吗
def remove_old_departure_dates(flights, search_date):
new_flights = defaultdict(lambda : defaultdict(list))
s_date = datetime.strptime(search_date,'%m/%d/%y')
for key in flights.keys():
dep_date = datetime.strptime(key.DDATE,'%m/%d/%y')
if(s_date > dep_date):
del flights[key]
new_flights = copy.deepcopy(flights)
flights.clear()
return new_flights
def remove_old_departure_dates(flights, search_date):
new_flights = defaultdict(lambda : defaultdict(list))
s_date = datetime.strptime(search_date,'%m/%d/%y')
for key in flights.keys():
dep_date = datetime.strptime(key.DDATE,'%m/%d/%y')
if(s_date > dep_date):
new_flights[key] = flights[key]
flights.clear()
return new_flights
基于这些评论,我做了以下操作,并使用deepcopy删除了引用。好像起作用了。这是正确的吗?你知道吗
def remove_old_departure_dates(flights, search_date):
old_flights = defaultdict(lambda : defaultdict(list))
new_flights = defaultdict(lambda : defaultdict(list))
s_date = datetime.strptime(search_date,'%m/%d/%y')
for key in flights.keys():
dep_date = datetime.strptime(key.DDATE,'%m/%d/%y')
if(s_date > dep_date):
print "removing dates " + key.DDATE +" "+search_date
old_flights[key] = copy.deepcopy(flights[key])
else:
new_flights[key] = copy.deepcopy(flights[key])
return (old_flights, new_flights)
目前没有回答
相关问题 更多 >
编程相关推荐