在 python 中,我想从一个较大的字符串列表中打印一个较小的随机选择字符串列表,返回 n 个项目。但是,生成的较小列表必须应用条件,以便某些项目不能一起存在于新的较小列表中。
以我正在研究的这个例子为例:使用 python,我想随机生成 2 个独特的运动队(team1
, ,每个有 5 名球员)从可用球员的组合列表( ,总共 10 名球员team2
)中相互对抗。players_available
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 库(最好尽可能少)的解决方案。