我有两个包含两个类实例的列表。 我想将第一个列表中的项目组分配给第二个列表。我有正确的方法add_agent。 我只是不知道如何以正确的顺序迭代和排除两个列表。
例如: 20个分配给0个家庭的代理0,1,2,3或4个随机组。
到目前为止我的代码:
{{1}}
非常感谢!
答案 0 :(得分:1)
您可以使用random.sample
选择随机的家庭组,然后分配代理:
def allocate_to_family(families, agents):
for dummy_family in families:
for dummy_agent in random.sample(agents, 4):
dummy_family.add_agent(dummy_agent)
答案 1 :(得分:1)
你非常接近你想做的事情。实际上,我只是将您的代码修改为所需的效果:
# We go through each family
for family in families:
# For each family, we go through the agents in the agents list
count = random.randint(0, 4)
assigned = []
for agent in agents:
# We assign 0-4 agents. If there are no free agents left then we
# won't assign any
if count == 0:
break
else:
count--;
family.add_agent(agent)
# Remove that agent once we assigned him, but we can't remove
# inside a for loop, so we store it inside a list to remove later
assigned.append(agent);
# This is a one-liner that remove elements in sublist from list I found
agents = [x for x in agents if x not in assigned]
基本上,我们需要从原始列表中删除已分配的代理,否则将重复分配它们。由于我们处于for循环中,我们需要将它们存储在临时列表中并在以后删除它们,因为当我们循环它时禁止修改列表。
我也想指出一个单独的解决方案。我们可以循环遍历每个代理,然后随机选择一个系列,检查它是否少于四个代理,然后将代理添加到该系列。否则尝试找一些少于四个代理的其他家庭。但是,这需要您了解一个家庭的当前代理数量。我假设在以下代码中为family.numberOfAgents()
:
for agent in agents:
family = False
# This loop exits after finding a valid family
while !family:
family = numpy.random.choice(families)
if family.numberOfAgents() >= 4:
family = False
# Finally add the agent
family.add_agent(agent)