[英]list named with a function argument in python
I get the feeling this is probably something I should know but I can't think of it right now. 我觉得这可能是我应该知道的,但我现在无法想到。 I'm trying to get a function to build a list where the name of the list is an argument given in the function;
我试图得到一个函数来建立一个列表,其中列表的名称是函数中给定的参数;
eg 例如
def make_hand(deck, handname):
handname = []
for c in range(5):
handname.append(deck.pop())
return handname
# deck being a list containing all the cards in a deck of cards earlier
The issue is that this creates a list called handname when i want it to be called whatever the user enters as handname when creating the hand. 问题是,当我希望创建手时,无论用户输入什么作为手名,它都会创建一个名为手名的列表。
Anyone can help? 有人可以帮忙吗? thanks
谢谢
You can keep a dictionary where the keys are the name of the hand and the values are the list. 您可以保留一个字典,其中的键是手的名称,值是列表。
Then you can just say dictionary[handname] to access a particular hand. 然后,您只需说出dictionary [handname]即可访问特定的手。 Along the lines of:
遵循以下原则:
hands = {} # Create a new dictionary to hold the hands.
hands["flush"] = make_hand(deck) # Generate some hands using your function.
hands["straight"] = make_hand(deck) # Generate another hand with a different name.
print hands["flush"] # Access the hand later.
While you can create variables with arbitrary names at runtime, using exec
(as sykora suggested), or by meddlings with locals
, globals
or setattr
on objects, your question is somewhat moot. 尽管您可以在运行时使用
exec
(如sykora所建议的那样)或通过对对象的locals
, globals
或setattr
进行干预来创建具有任意名称的globals
,但您的问题有些疑问。
An object (just about anything, from integers to classes with 1000 members) is just a chunk of memory. 一个对象(几乎所有东西,从整数到具有1000个成员的类)都只是一块内存。 It does not have a name, it can have arbitrarily many names, and all names are treated equal: they just introduce a reference to some object and prevent it from being collected.
它没有名字 ,它可以有任意多的名称,并且所有名称被视为平等的:他们只是介绍一些对象的引用,并防止它被收集。
If you want to name items in the sense that a user of your program gives a user-visible name to an object, you should use a dictionary to associated objects with names. 如果要以程序用户为对象提供用户可见的名称的方式命名项目,则应使用字典将对象与名称相关联。
Your approach of user-supplied variable names has several other severe implications: * what if the user supplies the name of an existing variable? 您使用的用户提供的变量名的方法还有其他严重的含义:*如果用户提供了现有变量的名称该怎么办? * what if the user supplies an invalid name?
*如果用户提供了无效的名称怎么办?
You're introducing a leaky abstraction , so unless it is really, really important for the purpose of your program that the user can specify a new variable name, the user should not have to worry about how you store your objects - an not be presented with seemingly strange restrictions. 您正在引入一个泄漏的抽象 ,因此,除非对于程序的目的而言,用户可以指定一个新的变量名真的非常重要,否则用户不必担心如何存储对象-不会出现有看似奇怪的限制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.