开发者

How to make lists automatically instantiate on use in Python as they do in Perl?

开发者 https://www.devze.com 2022-12-28 04:46 出处:网络
In Perl, I can do this: push(@{$h->[x]}, y); Can I simplify the foll开发者_运维问答owing python codes according to above Perl example?

In Perl, I can do this:

push(@{$h->[x]}, y);

Can I simplify the foll开发者_运维问答owing python codes according to above Perl example?

if x not in h:
  h[x] = []
h[x].append(y)

I want to simplify this, because it goes many places in my code, (and I cannot initialize all possible x with []). I do not want to make it a function, because there is no 'inline' keyword.

Any ideas?


A very elegant way (since Python 2.5) is to use defaultdict from the "collections" module:

>>> from collections import defaultdict
>>> h = defaultdict(list)
>>> h['a'].append('b')
>>> h
defaultdict(<type 'list'>, {'a': ['b']})

defaultdict is like a dict, but provides a default value using whichever constructor you passed to it when you created it (in this example, a list).

I particularly like this over the setdefault dict method, because 1) you define the variable as a defaultdict, and generally no other changes are required on the code (except perhaps to remove previous kludges for default values); and 2) setdefault is a terrible name :P


There are a couple of ways to do this with the dict methods:

h.setdefault(x, []).append(y)

or

h[x] = h.pop(x,[]).append(y)


You can use setdefault

h = {}
h.setdefault(x, []).append(y)
0

精彩评论

暂无评论...
验证码 换一张
取 消