pacodelumberg pacodelumberg - 3 months ago 26
Python Question

python map string split list

I am trying to map the

str.split
function to an array of string. namely, I would like to split all the strings in a string array that follow the same format. Any idea how to do that with
map
in python? For example let's assume we have a list like this:

>>> a = ['2011-12-22 46:31:11','2011-12-20 20:19:17', '2011-12-20 01:09:21']


want to split the strings by space ( split(" ")) using map to have a list as:

>>> [['2011-12-22', '46:31:11'], ['2011-12-20', '20:19:17'], ['2011-12-20', '01:09:21']]

Answer

Though it isn't well known, there is a function designed just for this purpose, operator.methodcaller:

>>> from operator import methodcaller
>>> a = ['2011-12-22 46:31:11','2011-12-20 20:19:17', '2011-12-20 01:09:21']
>>> map(methodcaller("split", " "), a)
[['2011-12-22', '46:31:11'], ['2011-12-20', '20:19:17'], ['2011-12-20', '01:09:21']]

This technique is faster than equivalent approaches using lambda expressions.