Python:从列表中打印n个随机项,但输出必须满足多个规则



在python中,我想从一个较大的字符串列表中打印一个较小的随机选择字符串列表,返回n个项目。但是,生成的较小列表必须具有适用于它的条件,以便某些项目不能一起存在于新的较小列表中。

以我正在研究的这个例子为例:使用python,我想从可用球员的组合列表(players_available,总共10名球员(中随机生成2个独特的运动队(team1team2,各有5名球员(进行比赛。

players_available是手动预定义的,以玩家名称列表的形式存在,如"汤姆"、"露西"one_answers"詹姆斯。然而,"汤姆"one_answers"詹姆斯"不可能存在于同一支球队中(例如,因为他们都太好了,不能在同一支队伍中打球!(。总共有大约10条规则。

我该如何在python中执行此操作?我已经设法从主列表中打印了两个唯一的列表,但我不确定应用规则的最佳方式;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库(最好是尽可能少的库(来找到解决方案。

您可以打乱列表,取前半部分并根据规则进行检查。如果所有规则都返回True,则可以停止洗牌。

这种方法非常基本,不太可能适应大量玩家和规则,因为你不会在每次洗牌后从池中淘汰玩家。然而,由于尺寸小和限制,这不是一个问题。

import random
def rules(team):
separate = ['Tom','James']
together = ['Josh','Gordon']
best = ['Steve','Mike']

s = sum([x in team for x in separate]) == 1
t = all([x in team for x in together]) or not all([x in team for x in together])
b = sum([x in team for x in best]) == 1
return s & t & b

players_available = ['Tom', 'Lucy', 'James', 'Josh', 'Steve', 'Mike', 'Darren', 'Joe', 'Delia', 'Gordon']
while True:
random.shuffle(players_available)
t1 = players_available[:5]
t2 = players_available[5:]
if rules(t1):
break


print(t1,t2, sep='n')

输出

['Lucy', 'Mike', 'James', 'Joe', 'Gordon']
['Delia', 'Steve', 'Tom', 'Josh', 'Darren']

相关内容

  • 没有找到相关文章

最新更新