Home

Previous Entry | Next Entry

Mutators

  • Nov. 8th, 2007 at 2:06 PM
obscure
Let us consider the following code to loop over the keys from a dictionary in Python:

  for key in a_dict.keys():
This would be nearly the same in Perl:

  for my $key in (keys %a_dict) {
And Perl 6*:

  for %a_dict.k -> my $key {
But now you say: I want to have in a sorted rather then arbitrary order!

In Python you have to allocate a temporary variable, sort it, then loop over the result:

  the_keys = a_dict.keys()
  the_keys.sort()
  for key in the_keys:
Where as Perl takes a functional approach that is, in my opinion, a lot clearer:

  for my $key in (sort keys %a_dict) {
And Perl 6*:

  for sort %a_dict.k -> my $key {
* I vaguely recall something about the temporary variables used in loops not requiring an explicit "my" but I can't seem to find something saying that explicitly now.

[Edit] So as many people pointed out to me, this was fixed for Python as of 2.4 (my laptop and work machines all use 2.3) with: for key in sorted(a_dict.keys()): What's more, the .keys() is assumed so you can actually just do for key in a_dict: or for key in sorted(a_dict):

Comments

[info]radiotelescope wrote:
Nov. 23rd, 2007 05:16 pm (UTC)
Very belated:

for val in sorted(dic.keys()): ...

or even

for val in sorted(dic): ...
[info]radiotelescope wrote:
Nov. 23rd, 2007 05:21 pm (UTC)
(That's Python 2.4.)
[info]daerr wrote:
Nov. 26th, 2007 06:53 pm (UTC)
Yeah, I'd been meaning to to post something about this having learned about sorted() after having posted. Didn't know about the non-keys form... is val a pair in that case? (Is a pair a concept in python?)
[info]radiotelescope wrote:
Nov. 28th, 2007 06:17 pm (UTC)
Python has pairs, but "for key in dic" iterates through the keys. To iterate through pairs, you'd say "for pair in dic.items()". Or, more likely, "for (key, val) in dic.items()".

"sorted(dic.items())" is legal, because it sorts pairs by the first column and then the second column.

Latest Month

January 2008
S M T W T F S
  12345
6789101112
13141516171819
20212223242526
2728293031  

Tags

Powered by LiveJournal.com