Hacker News new | ask | show | jobs
by scienceman 1871 days ago
Most "straightforward" way I could think of:

```

import itertools, collections

cnt = itertools.count(1)

d = collections.defaultdict(lambda: next(cnt))

s = "abcad"

[d[c] for c in s]

```

1 comments

Oh, this is nice. You can do it in one line (plus imports) with

  d = defaultdict(count().__next__)
Interesting... I wonder if this is vulnerable to getting garbaged collected at any point during execution.
No, the __next__ slot wrapper holds a reference to its associated count object.