[英]Why aren't dictionaries callable?
It's a usual programming problem to have a list of objects that you want to map into another. 拥有要映射到另一个对象的列表是一个常见的编程问题。 This is usually done with a dictionary:
通常使用字典来完成:
l1=[1,2,3]
d={1:'_ONE', 2:'_TWO', 3:'_THREE'}
l2= [d[i] for i in l1]
In many cases, it's natural to see a dictionary as a function that maps keys to values. 在许多情况下,很自然地将字典视为将键映射到值的函数。 Then, you'd simply
l2= map(d,l1)
instead of using the list comprehension (or the ugly map(d.__getitem__,l1)
. 然后,您只需使用
l2= map(d,l1)
而不是使用列表map(d.__getitem__,l1)
(或使用丑陋的map(d.__getitem__,l1)
。
Of course, since python is so flexible, you can get this behaviour easily: 当然,由于python非常灵活,因此您可以轻松获得以下行为:
class CallableDict(dict):
def __call__(self, k):
return self[k]
but this obviously doesn't work when accessing dicts you don't create yourself. 但这在访问您未创建的字典时显然不起作用。
Are there good reasons why the base python dictionaries are not callable by default? 是否有充分的理由为什么默认情况下无法调用基本python字典?
Disclaimer: The motivation for this question is mostly ruby, where dictionaries work this way 免责声明:这个问题的动机主要是红宝石,字典在这种情况下工作
There should be one-- and preferably only one --obvious way to do it.
应该有一种-最好只有一种-显而易见的方法。 http://legacy.python.org/dev/peps/pep-0020/
http://legacy.python.org/dev/peps/pep-0020/
If you make dict
callable to subscript a dictionary, now you have two ways of doing the same thing: 如果使
dict
可用于下标字典,那么现在您可以通过两种方式执行同一操作:
d[k] # Existing
d(k) # Proposed
Even the case that you bring up, having a callable to pass to map
, already has one obvious solution: 即使您提出了具有可调用传递给
map
,也已经有了一个显而易见的解决方案:
map(d.get, it) # Existing
map(d, it) # Proposed
There doesn't seem to be any particular advantage to your proposal, and it duplicates what are already obvious ways. 您的提案似乎没有任何特别的优势,并且它已经复制了已经显而易见的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.