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']]
We can also use the map() function to convert a list of strings to a list of numbers representing the length of each string element i.e. It iterates over the list of string and apply len() function on each string element. Then stores the length returned by len() in a new sequence for every element.
split() will split that input into a list of “words”; map(int, ...) will call int on each word, it will to that lazily (although that is not important here); and. x, y = ... will unpack the expression into two elements, and assign the first one to n and the second one to S .
Python String split() MethodThe split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
n, S = map(int, input().split()) will query the user for input, and then split it into words, convert these words in integers, and unpack it into two variables n and S .
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.
map(lambda x: x.split(), a)
but, using a list comprehension [x.split() for x in a]
is much clearer in this case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With