Technology, politics and the rest
Header picture

Python

I’m finally getting better at python. I was working on a script today that generated a histogram, and it had to do all sorts of things with long lists of numbers. The python ways to do these things are much more concise.

For example, let’s say I have two lists:

>>> a = [2, 5, 9, 12, 19]
>>> b = [1, 5, 3, 8, 14, 21, 8, 5, 2]

I might want to generate a list the same size as a where the value of each element is equal to the number of items in b that are less than the corresponding value in a. In other words, the first entry would be the number of elements in b that are less than 2, the second element would be the number less than 5 and so on.

If you’re thinking in C, it’s certainly not hard, just two for loops. In python, you can do:

>>> [len(filter(lambda x: x < y, b)) for y in a]
[1, 3, 7, 7, 8]

How does it work? Well working from the outside in:
The [* for y in a] makes y iterate through every element in a. filter(lambda x: x < y, b) returns all the elements in b that are less than y (which is the current value from a). Getting the len() of this list tells you how many elements are in the filter output, i.e. how many items are less than y. There are a bunch of other ways to do this, and in real life you’d want to make it a bit easier to read, but it’s cool to be able to express operations like that.

Hopefully this makes sense to someone.. my explanations aren’t too good.

In other news, I got a book on Ruby on Rails recently, which I’ve already read a lot of via PDF, but I’m looking forward to spending more time with it.

April 10, 2007   No Comments