<分区>
在 python 中,我想从较大的字符串列表中打印较小的随机选择字符串列表,返回 n 个项目。但是,生成的较小列表必须应用条件,以便某些项目不能一起存在于新的较小列表中。
以我正在研究的这个例子为例:我想使用 python 随机生成 2 个独特的运动队(team1
、team2
,每队有 5 名球员)进行比赛从可用玩家的组合列表中相互对抗(players_available
,总共 10 个玩家)。
players_available
是手动预定义的,作为玩家名称列表存在,例如“Tom”、“Lucy”和“James”。但是,'Tom' 和 'James' 不能存在于同一个团队中(因为,例如,他们都太棒了,不能在同一个团队中打球!)。总共有大约 10 条规则。
我将如何在 python 中执行此操作?我已经设法从主列表打印 2 个唯一列表,但我不确定将规则和条件应用于 2 个输出列表的最佳方法。这是我所在的位置:
# Sports match team selection script (2 teams of 5 players each team)
import random
# available players (always an even number of items in this list. Could be 10, 12 or 14)
players_available = ['Tom', 'Lucy', 'James', 'Josh', 'Steve', 'Mike', 'Darren', 'Joe', 'Delia', 'Gordon']
# number of players required per team (will always be half the number of players available)
n = 5
# current top 2 players (manually chosen)
best1 = 'Steve'
best2 = 'Mike'
# selection rules (only written here as descriptive strings for clarity. NOT currently implemented in team selection code below! How would I do this properly?)
rule1 = 'Tom and James cant be on the same team'
rule2 = 'Josh must be on the same team as Gordon'
rule3 = 'best1 and best2 cant be on the same team'
# etc etc... until rule 10 (there'll be no more than 10 rules)
# generate team 1
team1 = random.sample(players_available, n)
print(team1)
# remaining players
players_remaining = players_available
for player in team1:
if player in players_remaining:
players_remaining.remove(player)
# create team 2
team2 = players_remaining
print(team2)
我不是 Python 专家,所以我正在尝试使用基本的 Python 原则(即大量 if/elif 语句?)和核心 Python 库(最好尽可能少)找出解决方案。