mik*_*ike 79 python autovivification
在Perl很多次,我会做这样的事情:
$myhash{foo}{bar}{baz} = 1
Run Code Online (Sandbox Code Playgroud)
我怎么把它翻译成Python?到目前为止,我有:
if not 'foo' in myhash:
myhash['foo'] = {}
if not 'bar' in myhash['foo']:
myhash['foo']['bar'] = {}
myhash['foo']['bar']['baz'] = 1
Run Code Online (Sandbox Code Playgroud)
有没有更好的办法?
Joh*_*uhy 105
如果您需要的嵌套量是固定的,那就collections.defaultdict太棒了.
例如筑巢两个深:
myhash = collections.defaultdict(dict)
myhash[1][2] = 3
myhash[1][3] = 13
myhash[2][4] = 9
Run Code Online (Sandbox Code Playgroud)
如果你想进入另一层嵌套,你需要做类似的事情:
myhash = collections.defaultdict(lambda : collections.defaultdict(dict))
myhash[1][2][3] = 4
myhash[1][3][3] = 5
myhash[1][2]['test'] = 6
Run Code Online (Sandbox Code Playgroud)
编辑:MizardX指出我们可以通过一个简单的函数获得完全的通用性:
import collections
def makehash():
return collections.defaultdict(makehash)
Run Code Online (Sandbox Code Playgroud)
现在我们可以做到:
myhash = makehash()
myhash[1][2] = 4
myhash[1][3] = 8
myhash[2][5][8] = 17
# etc
Run Code Online (Sandbox Code Playgroud)
nos*_*klo 97
class AutoVivification(dict):
"""Implementation of perl's autovivification feature."""
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
Run Code Online (Sandbox Code Playgroud)
测试:
a = AutoVivification()
a[1][2][3] = 4
a[1][3][3] = 5
a[1][2]['test'] = 6
print a
Run Code Online (Sandbox Code Playgroud)
输出:
{1: {2: {'test': 6, 3: 4}, 3: {3: 5}}}
Run Code Online (Sandbox Code Playgroud)
zwe*_*nde 13
是否有理由需要成为决定词?如果这个特定结构没有令人信服的理由,你可以简单地用一个元组索引dict:
mydict = {('foo', 'bar', 'baz'):1} # Initializes dict with a key/value pair
mydict[('foo', 'bar', 'baz')] # Returns 1
mydict[('foo', 'unbar')] = 2 # Sets a value for a new key
Run Code Online (Sandbox Code Playgroud)
如果使用元组键初始化dict,则必须使用括号,但在使用[]设置/获取值时可以省略它们:
mydict = {} # Initialized the dict
mydict['foo', 'bar', 'baz'] = 1 # Sets a value
mydict['foo', 'bar', 'baz'] # Returns 1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
72591 次 |
| 最近记录: |