因此,我有一个从CSV文件“播放器和排名”中导入的列表,因此该列表类似于:
Players = [['Tony', 3], ['Mike', 6], ['John', 9], ['Will', 7]]
我想利用球员的排名为每位球员创造力量,以便拥有更高力量的人有更高的获胜机会,例如排名第一的玩家更有机会赢得比赛,但我不知道如何实现。
到目前为止,这是我仅导入csv的代码:
def import():
players = []
with open('players.csv', 'r') as csvfile:
reader = csv.DictReader(csvfile, delimiter=',')
for row in reader:
player.append([row['Player'], int(row['Ranking'])])
for item in player:
print(item)
答案 0 :(得分:2)
这是一种方法(不创建class Player
,尽管从长远来看这样做可能是更好的方法):
import csv
def import_players(filename):
players_list = []
with open(filename, 'r', newline='') as csvfile:
reader = csv.DictReader(csvfile, delimiter=',')
for row in reader:
rank = int(row['Ranking'])
strength = rank*2 - 1 # Calculate from rank somehow...
players_list.append([row['Player'], rank, strength])
return players_list
players = import_players('players.csv')
for player in players:
print(player)
输出:
['Tony', 3, 5]
['Mike', 6, 11]
['John', 9, 17]
['Will', 7, 13]
为进行比较,可以通过首先定义一个Player
类来做到这一点:
import csv
class Player:
def __init__(self, name, rank):
self.name = name
self.rank = rank
self.strenth = rank*2 - 1 # Calculate from rank somehow...
def __repr__(self):
return '{}(name={!r}, rank={!r}, strength={!r})'.format(
type(self).__name__, self.name, self.rank, self.strenth)
def import_players(filename):
players_list = []
with open(filename, 'r', newline='') as csvfile:
for row in csv.DictReader(csvfile, delimiter=','):
rank = int(row['Ranking'])
# Note strength will be calculated and added by the class constructor.
players_list.append(Player(row['Player'], rank))
return players_list
players = import_players('players.csv')
for player in players:
print(player)
输出:
Player(name='Tony', rank=3, strength=5)
Player(name='Mike', rank=6, strength=11)
Player(name='John', rank=9, strength=17)
Player(name='Will', rank=7, strength=13)
答案 1 :(得分:1)
正如其他人所建议的那样,我强烈建议为您的每个玩家创建一个课程。
class Player:
def __init__(self, name, strength):
self.name = name
self.strength = strength
创建了Player
类后,您可以使用以下方法创建players
列表:
players = [Player('Tony',3), Player('Mike',6), Player('John',9), Player('Will',7)]
最后,我建议您对球员列表进行排序,以使列表中Player
的第一个实例具有最高的strength
。
players.sort(key=lambda x: x.strength, reverse=True)
要查看订单的更改方式,您可以执行以下操作:
for player in players:
print(json.dumps(player.__dict__))
您将看到以下输出:
{"name": "John", "strength": 9}
{"name": "Will", "strength": 7}
{"name": "Mike", "strength": 6}
{"name": "Tony", "strength": 3}
现在,您只需要确定想要如何计算获胜者,我们将需要更多信息。
一种解决方案是重新定义Player
类,以使每个Player
具有一个points
属性,该属性随每次迭代增加。 strength
属性将成为每次迭代可能产生的最大点数。第一个达到100分的玩家获胜。
此方法的示例实现可能如下所示:
import json
import random
class Player:
def __init__(self, name, strength):
self.name = name
self.strength = strength
self.points = 0
self.point_history = list()
players = [Player('Tony',3), Player('Mike',6), Player('John',9), Player('Will',7)]
players.sort(key=lambda x: x.strength, reverse=True)
while not any(player.points >= 100 for player in players):
for player in players:
points = random.randint(0, player.strength)
player.points += points
player.point_history.append(points)
print(f'{player.name} earned {points} points and now has a total of {player.points} points!')
if player.points >= 100:
break
for player in players:
print(json.dumps(player.__dict__))
答案 2 :(得分:0)
如果您的问题是如何基于排名来表示实力,从而使玩家获胜的概率取决于其排名,则可以将strength
表示为范围元组(例如(3, 9)
)。 / p>
将这些范围分配给玩家的一条规则可以是:
p
的范围是从0到所有等级的总和(其中p
是玩家的总数),以便根据玩家的等级编号来创建范围这是一个实现:
players = [['Tony', 3], ['Mike', 6], ['John', 9], ['Will', 7]]
players.sort(key=lambda x: x[1])
# create strength ranges
strengths = []
i = 0
for p in players:
strengths.append((i, i + p[1]))
i += p[1]
# assign strengths in reverse order
for p in players:
p.append(strengths.pop())
print(players)
# [['Tony', 3, (16, 25)], ['Mike', 6, (9, 16)], ['Will', 7, (3, 9)], ['John', 9, (0, 3)]]
现在假设我们与random.randint
进行随机骰子游戏,我们可以看到这些范围如何确定获胜者:
import random
from collections import Counter
sum_ranks = sum(p[1] for p in players)
winners = []
for game in range(100):
dice_roll = random.randint(0, sum_ranks - 1)
winning_player = [p for p in players if dice_roll >= p[2][0] and dice_roll < p[2][1]][0]
winners.append(winning_player[0])
print(Counter(winners))
# Counter({'Tony': 39, 'Mike': 35, 'Will': 14, 'John': 12})
对于其他几个实验,我们看到以下结果(计数器对象中的数字代表玩家赢得了多少场比赛):
Counter({'Tony': 32, 'Mike': 29, 'Will': 27, 'John': 12})
Counter({'Tony': 33, 'Will': 29, 'Mike': 28, 'John': 10})
Counter({'Tony': 45, 'Mike': 28, 'Will': 16, 'John': 11})
Counter({'Tony': 34, 'Will': 28, 'Mike': 27, 'John': 11})
Counter({'Tony': 39, 'Mike': 35, 'Will': 20, 'John': 6})