重载列表理解行为?
我的任务是创建一个硬件笼模型。每个笼子包含 N 个插槽,每个插槽可能包含也可能不包含卡片。
我想使用列表来模拟笼子。每个列表索引将对应于槽号。 cards[0].name="Card 0"
等。
这将允许我的用户通过简单的列表理解来查询模型。例如:
for card in cards:
print card.name
我的用户不是熟练的 Python 用户,他们将与模型实时交互,因此让列表索引不对应于填充的卡片是不切实际的。换句话说,如果用户移除一张卡,我需要执行一些操作来指示该卡未填充 - 我的第一反应是将列表项设置为 None
。
老板喜欢这个方案,但他并不热衷于上面的列表理解如果缺少一张卡片就会失败。 (目前确实如此。)他甚至不太支持要求用户学习足够的 Python 来创建忽略 None
的列表理解表达式。
我的想法是对 list
类进行子类化,以创建一个 newclass
。它的工作方式与列表完全相同,但 for card in cards
只会返回未设置为 None
的成员。
有人可以演示如何重载列表类,以便子类上调用的列表推导式将忽略 None
吗? (到目前为止,当我尝试这样做时,我的 Python 技能已经开始下降。)
任何人都可以提出更好的方法吗?
I'm tasked with creating a model of a cage of hardware. Each cage contains N slots, each slot may or may not contain a card.
I would like to model the cage using a list. Each list index would correspond to the slot number. cards[0].name="Card 0"
, etc.
This would allow my users to query the model via simple list comprehensions. For example:
for card in cards:
print card.name
My users, which are not sophisticated Python users, will be interacting with the model in real-time, so it is not practical to have the list index not correspond to a populated card. In other words, if the user removes a card, I need to do something that will indicate that the card is not populated—my first impulse was to set the list item to None
.
The Bossman likes this scheme, but he's not crazy about the list comprehension above failing if there is a card missing. (Which it currently does.) He's even less supportive of requiring the users to learn enough Python to create list comprehension expressions that will ignore None
.
My thought was to sub-class the list
class, to create a newclass
. It would work exactly like a list, except for card in cards
would only return members not set to None
.
Will someone please demonstrate how to overload the list class so that list comprehensions called on the subclass will ignore None
? (My Python skills have so far begun to break down when I attempt this.)
Can anyone suggest a better approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以为此提供一个生成器/迭代器。
You could provide a generator/iterator for this.
如果您使用的是 2.6 或更高版本,您可以执行类似的操作来获取名称:
我认为这应该接近您想要的。
You can do something like this to get the names if you're using 2.6 or newer:
That should get close to what you're after I think.
也许定义一个函数(假设cards是一个全局变量?!?):
这样你的用户就可以简单地输入
pcards()
来获取列表。Perhaps define a function (assuming cards is a global variable?!?):
so your users can simply type
pcards()
to get a listing.