Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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']] 
like image 208
pacodelumberg Avatar asked Dec 11 '11 01:12

pacodelumberg


People also ask

How do you map a string to a list in Python?

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.

How do you split a map together in Python?

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 .

How do you split a string in a list?

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.

What is map int input () split ())?

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 .


2 Answers

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.

like image 137
Raymond Hettinger Avatar answered Sep 25 '22 14:09

Raymond Hettinger


map(lambda x: x.split(), a) but, using a list comprehension [x.split() for x in a] is much clearer in this case.

like image 26
Russell Dias Avatar answered Sep 25 '22 14:09

Russell Dias