3

在 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 库(最好尽可能少)的解决方案。

4

1 回答 1

1

您可以随机播放列表,选择前半部分并根据您的规则进行检查。如果所有规则都返回 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']
于 2021-12-14T15:07:05.743 回答