I came up with another nice little piece of python code to solve a problem while working on my blog client.
Here’s the deal. In order to support subcategories, I use a simple technique of separating the subcategories using a ‘.’ character. So to specify a category for something like armoire category, I would create the string ‘Woodworking.Armoire’. The blog software doesn’t recognize the category like that, however. Instead, it has separate categories for ‘Woodworking’ and ‘Armoire.’ So the string has to be split up.
That part is simple, as python has the ‘split’ method for strings. What’s more, categories are stored as a list so iterating through all the categories is as simple as a list comprehension.
The trick comes in that, perhaps, someone specifies multiple categories with multple levels of subcategories for each. So using the split method and a list comprehension I end up with a list of lists, each of unknown length. In order send this off to the blog, I need to create a single list.
The following piece of code does all of that:
categorylist = reduce(lambda l1, l2: l1 + l2,
[c.split('.') for c in categorylist])
The lambda just concatenates two lists, and the reduce
function handles iterating through each member of the list comprehension.
Imagine doing all that with C!