gpt4 book ai didi

python - 有效地更改列表列表中的值

转载 作者:太空宇宙 更新时间:2023-11-04 09:05:14 25 4
gpt4 key购买 nike

我有一个如下所示的列表:

[['B Borg', '3', '3', '1.0'], ['F Perry', '7', '8', '0.875'], ['R Nadal', '3', '5', '0.6']]

我希望用户从这些网球运动员中选择 2 人来打一场模拟网球比赛,随机选择获胜者。所以如果我选择 B Borg 和 F Perry 相遇,B Borg 随机获胜。最终结果应该是这样的:

[['B Borg', '4', '4', '1.0'], ['F Perry', '7', '9', '0.875'], ['R Nadal', '3', '5', '0.6']]

列表中的第 1 个元素是名称,第 2 个是赢得的比赛,第 3 个是总比赛次数,第 4 个是获胜百分比。

有什么“巧妙”的方法吗?我试过使用多个 if-elif-else block 。确保它有效,但它有很多文字。

最佳答案

使用类!!

class TennisPlayer(object):
def __init__(self,name,wins=0,games_played=0,win_pct=None):
self.name = name
self.wins = wins
self.games_played = games_played

# Note that although I do take win_pct as a parameter, I never use
# it anywhere. This trick may be useful for you if you end up maintaining
# code someone else has written and don't need part of their data
# structure anymore, but don't feel like refactoring code is worth the time

@property
def win_pct(self):
return self.wins/self.games_played

# as per lanzz, the @property token basically makes this a function that can
# be called like an instance variable.
#
# >>> player = TennisPlayer("Foo Bar",2,3) # 2 wins 1 loss
# >>> player.win_pct
# 0.6666666666666666
#
# You could probably make this prettier using string formatting.
# Something like return "{:.2f}%".format(self.wins/self.games_played*100)
# but it will make data manipulation much harder. Consider writing
# a TennisPlayer.print_stats() function that will just pretty print
# all the stats to stdout

def win_game(self,other):
self.games_played += 1
self.wins += 1
other.games_played +=1

lst = [['B Borg', '3', '3', '1.0'], ['F Perry', '7', '8', '0.875'], ['R Nadal', '3', '5', '0.6']]

tennisplayers = [TennisPlayer(*player) for player in lst]

# randomly choose B Borg (tennisplayers[0]) and F Perry (tennisplayers[1])

tennisplayers[0].win_game(tennisplayers[1])

您可以想象到它的实现方式。其中最好的(在我看来,无论如何)也是实现一个 TennisMatch 类:

class TennisMatch(object):
def __init__(self,player1,player2):
if type(player1) == list:
# implement special handlers for doubles games
else:
self.player1 = player1
self.player2 = player2

def play_match(self):
# do some stuff here
# to determine who wins and
# who goes crying to mommy
for player in [player1,player2]:
if player == winner: player.wins += 1
player.games_played += 1

然后你可以忽略我放在 TennisPlayer 类中的 def win_game,因为它实际上只是一个实现不佳的 setter。这样效果更好。

关于python - 有效地更改列表列表中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21296134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com