deepCopy是否复制从旧词典中删除后留下的空间?

2024-04-29 01:47:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试根据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()

两种方法都不起作用。内存没有被释放。你知道吗


源代码1

 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

源代码2

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)

Tags: keyinnewsearchdatetimedate源代码old