3 ms·
As a former Perl programmer, dabbling in Python, I keep getting reminded how awesome Perl is. For example: I'm collecting some stats indexed by (small) ints. I
by 1024core 9y ago
As a former Perl programmer, dabbling in Python, I keep getting reminded how awesome Perl is.
For example: I'm collecting some stats indexed by (small) ints. In Perl, I'd just say
$collection[$index] = $stat;
Try that in Python when $index is not received in order.
Edit: Fixed typo; meant "$stat" and not "%stat"
- kstrauser 9y agoIn Python: dict[index] = stat ...works much the same.
- arunix 9y agoThe Python version blows up if the slot isn't already populated. The Perl version works in either case (there is a typo in the Perl code though).
- amyjess 9y agoOnly if you're using a list, not a dict. I just tried it in the REPL: >>> foo = {} >>> foo[3] = 72 >>> foo[64] = 80 >>> foo {3: 72, 64: 80}
- arunix 9y agoThe difference is more dramatic once you have two or more dimensions: >>> foo = {} >>> foo[3][4] = 42 Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 3 Compared to: DB<1> $foo{3}{4} = 42 DB<2> x \%foo 0 HASH(0x7f9f4315c940) 3 => HASH(0x7f9f432bb148) 4 => 42
- pseudalopex 9y agotree = lambda: collections.defaultdict(tree) foo = tree() foo[3][4] = 42
- occams_chainsaw 9y agoI don't think I'd want or need to try that...
- zyxzkz 9y ago\%stat;
- deleted 9y ago[deleted]