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

标签 python python-3.x

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

[['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/

相关文章:

python - MultipleHiddenInput 仅在具有初始数据时呈现

python - 如果存在 np.nan,则删除数据帧字典中的所有数据帧

python - 为什么这个简单的 datetime.combine 操作不起作用?

python - PyQt 应用程序在 Linux 上卡住屏幕,在 Windows 上正常

python - 在python中的点后将 float 舍入为2位数字

python - 尽管数据库/模型中存在数据,FastAPI 并未选择嵌套模式

python - 在伽罗华域中生成反向元素

python - python线程中超时信号的替代方法

python - SQLITE创建语句错误

python - 导入枚举文件与 Python 2.7 不兼容