我有以下代码:
# Mec capacity to hold a vnf
served_vnfs = [0,1,2]
# All possible mec states as far as holded vnfs
mec_capacity_states = [copy.deepcopy(list(s)) for s in itertools.product(served_vnfs, repeat=2)]
# All possible states with defined number of mecs
mecs_states = [copy.deepcopy(list(p)) for p in itertools.product(mec_capacity_states, repeat=2)]
当我执行以下操作时:
mec_states[0][0][0] = 'A'
print(mec_states)
我得到的第一个值是:
[['A', 0], ['A', 0]]
这不是应该的,而是应该:
[['A', 0], [0, 0]],
我一直在使用copy.deepcopy()来避免这种情况,但我认为问题在于代码行:
mecs_states = [copy.deepcopy(list(p)) for p in itertools.product(mec_capacity_states, repeat=NUM_MECS)]
这个问题发生在子列表相等的任何组合中
我可以用什么替代品
使用deepcopy将为您提供一个数据结构,其中原始对象中的任何共享引用也会反映在副本中
如果要删除任何共享引用,可以使用json进行序列化和反序列化
请注意
deepcopy
将适用于任何python数据结构。只有当数据结构表现良好时,json方法才有效。它必须是非循环的,子类型必须是简单类型,如列表、整数、字符串等如果
served_vnfs
中的元素是简单的可序列化对象(例如整数),而不需要保留标识,那么序列化和反序列化列表列表(如@HåkenLid的answer肯定会起作用。但似乎有很多不必要的工作,特别是如果列表可能更长的话一种可能更简单的方法是复制从外部调用
itertools.product
返回的每个列表。由于这只是列表的浅表副本,因此无需使用copy
模块:测试(截断以避免滚动):
相关问题 更多 >
编程相关推荐