4 ms·
Most "straightforward" way I could think of: ``` import itertools, collections cnt = itertools.count(1) d = collections.defaultdict(lambda: next(cnt)) s =
by scienceman 5y 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]
```
- klyrs 5y agoOh, this is nice. You can do it in one line (plus imports) with d = defaultdict(count().__next__)
- scienceman 5y agoInteresting... I wonder if this is vulnerable to getting garbaged collected at any point during execution.
- klyrs 5y agoNo, the __next__ slot wrapper holds a reference to its associated count object.