itertools.product()的替代品?

2024-10-06 12:13:39 发布

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

我有以下代码:

# 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)]

这个问题发生在子列表相等的任何组合中

我可以用什么替代品


Tags: 代码inforproductlistcapacityrepeatitertools
2条回答

使用deepcopy将为您提供一个数据结构,其中原始对象中的任何共享引用也会反映在副本中

如果要删除任何共享引用,可以使用json进行序列化和反序列化

import json

# All possible states with defined number of mecs
mecs_states = itertools.product(mec_capacity_states, repeat=2)
mecs_states = json.loads(json.dumps(list(mecs_states)))

请注意deepcopy将适用于任何python数据结构。只有当数据结构表现良好时,json方法才有效。它必须是非循环的,子类型必须是简单类型,如列表、整数、字符串等

如果served_vnfs中的元素是简单的可序列化对象(例如整数),而不需要保留标识,那么序列化和反序列化列表列表(如@HåkenLidanswer肯定会起作用。但似乎有很多不必要的工作,特别是如果列表可能更长的话

一种可能更简单的方法是复制从外部调用itertools.product返回的每个列表。由于这只是列表的浅表副本,因此无需使用copy模块:

served_vnfs         = [0,1,2]
mec_capacity_states = list(itertools.product(served_vnfs, repeat=2))
mecs_states         = [list(map(list, p))
                       for p in itertools.product(mec_capacity_states,
                                                  repeat=2)]

测试(截断以避免滚动):

>>> mecs_states[0][0][0] = 'a'
>>> mecs_states
[[['a', 0], [0, 0]], [[0, 0], [0, 1]], [[0, 0], [0, 2]], [[0, 0], [1, 0]], ...

相关问题 更多 >