如何在 python 中创建一个由字符串组成的全局变量?
我正在尝试制作一款二十一点游戏。 我制作了抽牌和检查手牌总数是否超过 21 的功能,但仅限 3 名玩家。这很简单,我有 3 个清单。
但我想为 N 个玩家做这件事,所以我想保留我的功能并制作另一个在玩家和他们的手之间切换的功能。
def create_hands():
global total_players
for x in range(1, total_players+1):
vars()["hand_%d" % x] = []
print hand_1
我想为尽可能多的 N 个玩家(total_players)创建尽可能多的手牌,如 hand_1、hand_2 等...
由于上面的代码,我得到一个全局名称'hand_1'未定义错误
所以这一切都归结为:
如何使 "hand_%d" % x 全局化?
有更好的方法吗?
I'm trying to make a blackjack game.
I've made functions for drawing cards and checking if sum in one's hand exceeds 21 but only for 3 players. That was easy I had 3 lists.
But I want to do it for N number of players so I want to keep my functions and make another one that switches between players and their hands.
def create_hands():
global total_players
for x in range(1, total_players+1):
vars()["hand_%d" % x] = []
print hand_1
I want to create as many hands as in hand_1, hand_2, etc... for as many N players (total_players)
Because of the code above i get an global name 'hand_1' is not defined error
So it all comes down to:
How do I make "hand_%d" % x global ?
Is there a better way to do it ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,有更好的方法。只需创建一个列表列表即可。如果可能的话,应该忽略使用 vars。阅读和调试真的很难,你最近会后悔这种态度。当您创建类似
players ->; 的列表时手->卡
,或者甚至是玩家的字典,例如players['player1'][3]
代表玩家的三分之一卡,您会对此感到更加满意。Yes, there is a better way. Simply create a list of lists. Playing with vars should be ommited, if possible. It's really hard to read and debug and you will regret that attitude lately. When you create a list like
players -> hand -> cards
, or even a dict of players likeplayers['player1'][3]
for player's one third card, you will be much more happy with that.您遇到的问题是 vars() 是 locals() 的别名,在官方文档中有以下注释:
换句话说,向 vars() 添加键确实 NOT 不一定会更新本地 var iables 表(这就是为什么您会收到
global name hand_1 is not Defined
错误 -vars()[ "hand_1" ]
不会hand_1
到局部变量中)。正如 Gandi 提到的,有更简单的方法可以完成您想要做的事情 - 使用列表列表或类似的东西。有比创建任意命名的局部变量更传统的方法来解决这个问题。
The problem you are running into is that vars() is an alias for locals(), which has the following comment in the official documentation:
In other words, adding keys to vars() does NOT necessarily update the local var iables table (which is why you're getting the
global name hand_1 is not defined
error -vars()[ "hand_1" ]
doesn't makehand_1
into a local variable).As Gandi mentioned, there are far easier ways to do what you are trying to do - use a list of lists or something similar. There are far more conventional ways to solve this problem than creating arbitrarily-named local variables.
是的,有可以做到这一点。替换
为
但要警告的是,这个解决方案有点黑客,很容易导致问题(维护困难、失去对自发创建的变量的跟踪等)
Yes, it is possible to do that. Replace
with
Be warned however that this solution is kinda hackish and can easily lead to problems (difficulty in maintenance, losing track of the spontaneously created variables, etc.)