class Agent:
def __init__(self, state):
self.state = state
#initialize values
state_0_agents = 10
state_1_agents = 10
numberofselections = 2 #number of agents who can choose to transition to the higher plane
#list of agents
agents = [Agent(0) for i in range(state_0_agents)]
agents.extend(Agent(1) for i in range(state_1_agents))
random.choice(agents)
嘿!因此,我想从此“代理”列表中随机选择几个代理,其状态最终将变为1。不幸的是,随机选择功能会在所有元素中进行选择。但是我只想随机选择状态为0的那些。
我希望如果不创建新列表就可能发生这种情况。
最佳答案
我在这里看到3个选项:
random.choice([a for a in agents if a.state == 0])
random.choice()
调用循环放置,继续尝试直到获得符合条件的调用:while True:
agent = random.choice(agents)
if agent.state == 0:
break
agents
列表建立索引,然后从该索引中进行选择;这些实际上仍然只是列表:agent_states_index = {}
for index, agent in enumerate(agents):
agent_states_index.setdefault(agent.state, []).append(index)
agent_index = random.choice(agent_states_index[0])
agent = agents[agent_index]