Skip to main content
 首页 » 编程设计

python之使用装饰器与迭代来设置值

2025年05月04日9落叶无声

所以我必须遍历对象列表,使用它们的一些值进行计算,然后为它们分配新值。

因为列表中的许多项目将被分配相同的新值,所以我使用字典来保存需要相同值的项目列表。例如:

item_dict = {} 
 
for item in list: 
    value = item.value 
    if value not in item_dict: 
        item_dict[value] = [item] 
    else: 
        item_dict[value].append(item) 
 
# do some calculations base on values 
 
new_data # some dictionary created by computation 
# new data is stored new_data[value] = new_value 
 
for value, new_value in new_data.items(): 
    items = item_dict[value] 
    for item in items: 
        item.value = new_value 

我正在考虑使用装饰器删除 for item in items 循环,因为该列表的所有 new_value(s) 都是相同的。例如:

def dec(item): 
    def wrap(value): 
        item.value = value 
    return wrap 
 
def rec(item, func): 
    def wrap(value): 
        item.value = value 
        func(value) 
    return wrap 
 
item_dict = {} 
 
for item in list: 
    value = item.value 
    if value not in item_dict: 
        item_dict[value] = dec(item) 
    else: 
        item_dict[value] = rec(item, item_dict[value]) 
 
# do some calculations base on values 
 
new_data # some dictionary created by computation 
# new data is stored new_data[value] = new_value 
 
for value, new_value in new_data.items(): 
    items = item_dict[value] 
    items(new_value) 

装饰器时尚会更高效吗?它会对内存产生多大影响?有没有更好的方法来做到这一点?

请您参考如下方法:

defaultdict 在这里工作得很好:

from collections import defaultdict 
 
item_dict = defaultdict(list) 
 
for item in value_list: 
    item_dict[item.value].append(item) 
 
# do some calculations base on values 
 
new_data # some dictionary created by computation 
# new data is stored new_data[value] = new_value 
 
for value, new_value in new_data.items(): 
    for item in item_dict[value]: 
        item.value = new_value 

我很难想出装饰器版本可以更好的方法 - 一方面,您必须担心递归限制。