Back in the day, my advisor introduced me to the term of “just-in-time (JIT) learning.” We didn’t really have to define or ponder the term, it just made sense. Methods and syntax were secondary: we had to learn them on the fly, to achieve our lofty goals in the time alotted, which on the quarter system was very little. My fellow developers and I would trek out into the universe of docs and tutorials to find the techniques or methods we needed, well, just in time. This notion has grown on me over the years, and much of the work I’ve been called to do has involved some J.I.T. learning.
But while finding that programming silver bullet in online code/discussions/documentation is exciting, losing such gems is incredibly frustrating. I’ve found that refinding cool code tricks is difficult. How can you form a query for that one thing that you do, that allows you to write that script to iterate over that thing…? Yeah. Trudging through my old old code is painful. Googling for these silver bullets is even more painful. As an astute BayCHI lecturer (whose name I’ve forgotten) pointed out, the query term “Java” has been getting less and less valuable over the years, as the volume of Java web resources grows. So even if a slick query gets you that Ruby on Rails trick now, as the Ruby community grows, that link may be harder to find.
So on that note, I’d be thrilled to make this blog a chest in which we can keep these gems.
In python, there is a slick, but simple, technique for list generation:
>>> [word.upper() for word in ['this','is','such','a','great','list!']]
['THIS', 'IS', 'SUCH', 'A', 'GREAT', 'LIST!']
>>>
>>> [i for i in range (5)]
[0, 1, 2, 3, 4]
Thanks Marti!
n8 and ken-ichi simultaneously pointed out this addition to the technique:
>>> text = ['so', 'sayeth', 'thy', 'sweet', 'Lord']
>>> stopwords = ['the', 'thy', 'though']
>>> words = [token.upper() for token in text if token not in stopwords]
>>> words
['SO', 'SAYETH', 'SWEET', 'LORD']
So this has come in pretty handy for me, and I wouldn’t want to lose this gem. The goal for me is to minimize refinding and maximize things that go into my repertoire.
Whatever language or context, if it’s cool, and you think others will find it useful, put it here and tag it “codegem”
Here’s my list of useful Python basics. We should get n8 to install a syntax highlighting plugin…
Some of my favorite python functions:
map
>>> z = map(len, ["abc", "clouds", "rain"])
>>> z
[3, 6, 4]
lambda
>>> g = lambda u:u*u
>>> g(4)
16
filter
>>> x = [5,12,-2,13]
>>> y = filter(lambda z: z > 0, x)
>>> y
[5, 12, 13]
reduce
>>> x = reduce(lambda x,y: x y, range(5))
>>> x
10
walk
os.walk() performs recursion so you don’t have to!
correction — under reduce, it should be:
>>> x = reduce(lambda x,y: x + y, range(5))
oops!
>>> coders = [kueda, n8, k7, mangosquasher]>>> max(coders)
mangosquasher
I believe this construct you outline is called a list comprehension in Python.