python defaultdict tree,使用defaultdict的Python一线树。如何减少所需的参数数量?

I'm using this gist's defaultdict one-line tree.

def tree(): return defaultdict(tree)

Currently, you must provide a separate [] for every node you want to add.

ie:

users = tree()

users['harold']['username']['hrldcpr']

users['handler']['username']['matthandlersux']

My question is, how would I be able to flatten the input so that I could provide a list to achieve the same result?

ie:

users = tree()

users['harold', 'username', 'hrldcpr']

users['handler', 'username', 'matthandlersux']

Thanks for any help!

解决方案

You can simply define a funcion, say insert to create the node by providing a list and tree as argument.

def insert(tree, List):

for node in List:

tree = tree[node]

users = tree()

insert(users, ['harold', 'username', 'hrldcpr'])

would create a structure as {'harold' : {'username' : {'hrldcp' : {} } } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值