0

Ok, back to differences between 2.x and 3.x...

I have the following code to convert the sort key to a float:

def sort_key_func(row):
        return float(row[76][0:5])

which (under 2.x) returned the value of the field in the current row in position 76 for a lengthof 5. It was called like this:

filedata.sort(key=sort_key_func)

The problem I have now (which I think is a 3.x thing), is that I can't use row[76][0:5] any more because it now returns the 76th record, fields 1 through 5, instead of the 76th field for 5 positions. To get the field I need row[X][76][0:5] where [X] is the row.

Again, I'm kinda new to Python, and this 2.x to 3.x has thrown me.. Any ideas?

2
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by Tommymac501
0

Ok, back to differences between 2.x and 3.x...

I have the following code to convert the sort key to a float:

def sort_key_func(row):
        return float(row[76][0:5])

which (under 2.x) returned the value of the field in the current row in position 76 for a lengthof 5. It was called like this:

filedata.sort(key=sort_key_func)

The problem I have now (which I think is a 3.x thing), is that I can't use row[76][0:5] any more because it now returns the 76th record, fields 1 through 5, instead of the 76th field for 5 positions. To get the field I need row[X][76][0:5] where [X] is the row.

Again, I'm kinda new to Python, and this 2.x to 3.x has thrown me.. Any ideas?

I found a solution;

sorted(filedata, key=lambda a:a[76][0:5])

which bypasses the external function all together.

Help me out with the 'lambda' concept please. I understand it to mean more or less an 'in place' function? I don't really get how it works. I've read about it in several places, but none of the explinations really 'click'. My background is old time basic, VB, database programming and SQL. Does anyone have a simple explination for a 'Lambda' that might make sense to a layman?.

0

... I'll give it a shot, but I'm no expert at scripting language lambda expressions.

Lambda expressions are simply a way of defining a function without assigning a name to the function. They're sort of like function literals, in the same sense "cat" is a string literal and animalName might be associated with the value "cat".

Whenever you'd need a literal value where a value was expected (say, you call factorial(5) to get 120, rather than saying n=5;factorial(n)) you can have similar situations where a function literal might be good (you call plot(lambda x: x*x) instead of def squarefunc(x):return x*x; plot(squarefunc)).

So yeah, function literals. I think that's a fair comparison.

0

mmm ok, I see it now.. the plot example is what turned the light on.. thanks!!!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.