python 动态生成变量_从输入动态创建python变量?

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

您很可能不需要/不想通过用户输入定义变量名来存储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}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值