如何进行高级Python哈希自动修复? [英] How do I do advanced Python hash autovivification?

查看:217
本文介绍了如何进行高级Python哈希自动修复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是关于在Python中实现完整的Perl自动化。我知道以前提到类似的问题,到目前为止,最好的答案是在在Python中实现嵌套字典的最好方法是什么?但是,我希望这样做:

This question is about implementing the full Perl autovivification in Python. I know similar questions were asked before and so far the best answer is in "What is the best way to implement nested dictionaries in Python?" . However, I'm looking to do this:

a['x']['y'].append('z')

不声明 a ['x'] ['y'] = [] ,而不是声明 a ['x'] = {} 。 (在Perl中注意,你可以做 push @ {$ a-> {x} {y}},'z'; 。)

without declaring a['x']['y'] = [] first, or rather, not declaring a['x'] = {} either. (Note in Perl you can do push @{$a->{x}{y}}, 'z';.)

我知道 dict 列表类sorta不要混合,所以这很难,但是我有兴趣看看有人有巧妙的解决方案,可能涉及从 dict 创建一个继承的类,但是定义了一个新的附加方法呢?

I know dict and list classes sorta don't mix, so this is hard, but I'm interested in seeing if someone has an ingenious solution probably involving creating an inherited class from dict but defined a new append method on it?

我也知道这可能会抛弃一些Python纯粹主义者,要求我坚持使用Perl。但是,即使只是一个挑战,我想看一些东西。

I also know this might throw off some Python purists who will ask me to stick with Perl. But, even just for a challenge, I'd like to see something.

推荐答案

a = collections.defaultdict(lambda: collections.defaultdict(list))

这篇关于如何进行高级Python哈希自动修复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆