我在python 3中编写了一个程序,它模拟了不同玩家之间的竞争,这些玩家正在抛球。
我有一个包含玩家对象的列表,对象具有属性名称,平均投掷长度,投掷标准偏差,最后:表单列表的属性,其中每个索引包含玩家的多个投掷在eack比赛期间预制。 (为了澄清,在索引0上将有例如来自第一场比赛的6次投掷,在索引1处将有来自第二次比赛的6次投掷等等)。当然有多个球员。我现在需要找到一种方法来确定哪个玩家是每个比赛的赢家,并计算每个玩家的获胜次数。我总是发现赢家的事情,但这是我到目前为止所想到的:
def winner(self):
for player in players:
winner= max(players, key = attrgetter("self.results"))
通过此类创建Player对象:
class Player:
def __init__(self, name, mean, standardDeviation):
self.name = name
self.mean = mean
self.standardDeviation = standardDeviation
self.results = []
我很确定我上面写的内容不会让我到任何地方,所以你们有没有任何提示?
答案 0 :(得分:2)
这是一个只有简化Player
类的东西的版本,可以帮助您入门。它可以处理不止一个玩家将球投射到另一个玩家最长距离的关系。
class Player:
def __init__(self, name, results):
self.name = name
self.results = results
def find_winners(players, num_contests):
winners = [] # one (or more) player entries per contest
for icontest in range(num_contests):
contest_winners = [] # may hold multiple players if there are ties
contest_longest_throw = -1
for player in players:
player_longest_throw = max(player.results[icontest])
if player_longest_throw > contest_longest_throw:
contest_longest_throw = player_longest_throw
contest_winners = [player]
elif player_longest_throw == contest_longest_throw:
contest_winners.append(player)
winners.append(contest_winners)
return winners
# test data
players = [Player('Name1', [(7, 8, 9), (2, 3, 4), (3, 4, 5)]),
Player('Name2', [(4, 5, 6), (8, 9, 10), (6, 7, 8)]),
Player('Name3', [(1, 2, 3), (5, 6, 7), (9, 10, 11)]),
# add one that will tie with first player
Player('Name4', [(7, 8, 9), (2, 3, 4), (3, 4, 5)])]
# assumes length of first player's results is number of contests
winners_found = find_winners(players, len(players[0].results))
print("Contest Winner(s)")
for icontest, contest_winners in enumerate(winners_found, start=1):
print('{:^7} {}'.format(
icontest, ', '.join(player.name for player in contest_winners)))
输出:
Contest Winner(s)
1 Name1, Name4
2 Name2
3 Name3