【发布时间】:2022-01-17 21:12:32
【问题描述】:
在 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 库(最好尽可能少)的解决方案。
【问题讨论】:
-
我会尝试使用列表理解和一个函数来定义一个球员是否有资格进入给定的球队
-
无耻插件,但我基于第二个副本为斑马/爱因斯坦/消除难题编写了一个 python 求解器。这是非常简单的代码,您可能想在这里查看:github.com/madphysicist/puzzle-solvers/blob/master/src/…
标签: python zebra-puzzle