从输入动态创建python变量?

2024-09-27 00:19:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python创建一个盈亏跟踪器,遇到的问题是为每个可能的情况命名一个变量。显然,我无法预料到追踪器可能遇到的每一个案例(角色名称、游戏方法、游戏玩法等),但我仍然想跟踪这些东西。在

我正在创建一个变量来存储play的“method”的值,不管是字符还是其他什么。有没有一种方法可以接收用户的输入并将字符串转换成变量名,然后存储输赢?在

我做了一些研究,似乎许多类似的问题的答案都是“使用字典”,但是如果我“不能”预测字典的名称,我怎么能使用字典呢?在


Tags: 方法字符串用户名称游戏角色play字典
1条回答
网友
1楼 · 发布于 2024-09-27 00:19:15

解决问题的第一步就是准确地定义它。举个例子,说明你打算如何使用你的输赢追踪器,这将有助于明确你到底想做什么。在

您很可能不需要/不想通过用户输入定义变量名来存储wins。而是为每一组相关信息(例如来自一个用户的记录)创建一个字典。此词典将存储用户的名称、输赢计数等

我已经大致了解了你下面要找的东西。在

#create list 
gameTracker=[]

#method to get string input from user. Extremely basic solely to answer question. If you actually intend to get user input you'll need proper type checking in these functions
def inputString(Message):
    return raw_input(Message)

def inputInt(Message):
    return int(raw_input(Message))

#Replace "InputString('')" with whatever function is returning user input   
#Loop twice & input records for 2 players in gameTracker list. Each player's records is stored in a dictionary
for i in range(2):
    gameTracker.append(
    {"playerName":inputString("Input player name: "), "playerMethod":inputString("Input method: "),"gamePlayed":inputString("Input game: "),"wins":inputInt("Input wins: "),"losses":inputInt("Input losses: ")}
    )


#Print values for each player (dictionary), from gameTracker list   
for i in range(len(gameTracker)):
    print(gameTracker[i])

#Update the win count for player named 'peter'
for i in range(len(gameTracker)):

    if gameTracker[i]['playerName']=="peter":
        #get new win count- replace with whatever method does this for your application
        newWinCount=inputInt("Enter new win count: ")

        gameTracker[i]['wins']=newWinCount

        #Add one win to record for player 'peter'
        gameTracker[i]['wins']+=1

        print(gameTracker[i])

输出示例:

^{pr2}$

在更新玩家“彼得”的新赢点数到14+1后

{'playerName': 'peter', 'wins': 15, 'losses': 5, 'playerMethod': 
'character', 'gamePlayed': 'GTA'}

在字典中定义通过用户输入(根据您的请求)计算获胜数的键的名称。在

gameTracker.append(
{inputString("Input wins variable name: "):inputInt("Input wins: ")}
)   
print(gameTracker[0])   

上述报表输出

Input wins: 5
Input wins variable name: usr_peter_wns
{'usr_peter_wns': 5}

大多数时候,通过用户输入/变量定义键名并不是最好的解决方案。最好有可预测的名称,以便于操作。在

相关问题 更多 >

    热门问题