在oTree中基于布尔输入重新分组玩家的技术求助
Pythonic Solution for Player Grouping
Here's a cleaned-up, adaptable implementation that meets your requirements:
import random def after_all_players_arrive(group: Group): # Fetch all players from the group all_players = group.get_players() # Split players into participating/non-participating groups participating = [p for p in all_players if p.participating] non_participating = [p for p in all_players if not p.participating] # Handle odd participant count: move one random player to non-participating group if len(participating) % 2 != 0: moved_player = random.choice(participating) participating.remove(moved_player) non_participating.append(moved_player) # Optional: Update the player's participating status if needed # moved_player.participating = False # Shuffle participants to ensure random pairings random.shuffle(participating) # Split into groups of two (works for any even number of participants) game_groups = [participating[i:i+2] for i in range(0, len(participating), 2)] # Assign group identifiers to each player for easy reference for idx, game_group in enumerate(game_groups, start=1): for player in game_group: player.game_group = idx # Or store the group object directly # Mark non-participating players with a distinct group ID for player in non_participating: player.game_group = 0
Key Improvements & Breakdown:
- Clean List Comprehensions: Replace messy conditional loops with concise, readable splits for participating/non-participating players.
- Randomized Fairness: Uses
random.choice()to select a player to reassign when counts are odd, andrandom.shuffle()ensures unbiased pairings. - Flexible Pairing: The slicing pattern
participating[i:i+2]automatically creates groups of two regardless of how many even-numbered participants there are—works for any group size. - Explicit Attribute Assignment: Adds a clear
game_groupattribute to each player, making it straightforward to track their group later in your logic. - Removed Redundancies: Eliminated unused variables (like
number_players) and fixed incorrect list wrapping from the original code.
Notes:
- If
participatingis a method (not a boolean attribute), adjust the list comprehensions top.participating()instead ofp.participating. - The optional step to update the moved player's
participatingstatus depends on whether you need to reflect the change in their core field, or just group them separately. - This code adapts seamlessly to any initial group size, as long as
Group.get_players()returns an iterable ofPlayerobjects.
内容的提问来源于stack exchange,提问作者LWJones
相关产品推荐
相关产品推荐

