Perl Vs Python

Anton Muhin antonmuhin at sendmail.ru
Wed Feb 26 04:46:20 EST 2003


Several comments:

Derek Thomson wrote:
> 
> For example, Python doesn't allow hash slicing, so you can't do this:
> 
> my %hash = {};
> @hash{@list} = (1) x @list;
> 
> ... to create a set for fast membership testing. So all those neat
> little idioms Perl has for hash transformation are out. In Python list
> slices must be contiguous, so you can't do nifty one-line list
> shuffling, either. Pythoners will say all this is a feature. In Python,
> you would say something like:
> 
> hash = {}
> for item in list:
>    hash[item] = 1
> 
> ... to do the same thing. Again, clearer for the non-initiated. Some say
> that where Perl has "more than one way to do things", Python has "only
> one way to do one thing". That is of course, not true, but that's the idea.

It can be rather simply done in Python (at least in Python2.2):
l = ['a', 'b', 'c']
d = dict([(e, 1) for e in l])

> 
> Notice also that there are no "funny" character "$@%" in front of
> variables in Python, and it doesn't have different kinds of braces for
> different kinds of indexing. Everything in Python is a reference, so you
> don't have this typing problem. Therefore you can't get the contexts
> wrong. On the other hand, this means that there is no context, so the
> compiler can't work out what you're trying to do.
> 
> So, for something like:
> 
> $hash->{$name}->[$index] = 42
> 
> ... if there was no reference to an array in the hash at $name, one
> would be created. In Python, you have to check, and create one, if
> you're not sure, like in Java or C++. (And then you have to make sure
> the list is large enough for the index, as well). Assuming the lists are
> always MAX_INDEX in length then, to keep it simple:
> 
> if name not in hash:
>    hash[name] = [0] x MAX_INDEX
> 
> hash[name][index] = 42
> 
> ... or something along those lines.
> 

And again, if I understand you correctly, it can be done in Python:

h.setdefault(name, [0]*MAX_INDEX)[index] = 42

If you need this feature frequently, you can subclass dict.

Regards,
Anton.





More information about the Python-list mailing list