Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to convert strings from split function to ints in Python

I have a string of data with the following format: xpos-ypos-zoom (i.e. 8743-12083-15) that I want to split up and store in the variables xpos, ypos, and zoom. Since I need to do some calculations with these number I'd like to convert them to integers right from the beginning. Currently, the way I'm doing this is with the following code:

file = '8743-12083-15' xval, yval, zoom  = file.split("-") xval = int(xval) yval = int(yval) 

It seems to me there should be a more efficient way of doing this. Any ideas?

like image 209
Ian Burris Avatar asked Oct 15 '09 19:10

Ian Burris


People also ask

How do you convert from Split to int in Python?

To split a string into a list of integers: Use the str. split() method to split the string into a list of strings. Use the map() function to convert each string into an integer.

Can you convert strings to integers in Python?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed.

How do you parse a split string in Python?

Python string parsing walkthroughsplit(" ") >>> print type(mylist) <type 'list'> >>> print mylist ['What', 'does', 'the', 'fox', 'say? '] If you have two delimiters next to each other, empty string is assumed: el@apollo:~/foo$ python >>> mystring = "its so fluffy im gonna DIE!!!" >>> print mystring.

What is the best way to split a string in Python?

The 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.


2 Answers

My original suggestion with a list comprehension.

test = '8743-12083-15' lst_int = [int(x) for x in test.split("-")] 

EDIT:

As to which is most efficient (cpu-cyclewise) is something that should always be tested. Some quick testing on my Python 2.6 install indicates map is probably the most efficient candidate here (building a list of integers from a value-splitted string). Note that the difference is so small that this does not really matter until you are doing this millions of times (and it is a proven bottleneck)...

def v1():  return [int(x) for x in '8743-12083-15'.split('-')]  def v2():  return map(int, '8743-12083-15'.split('-'))  import timeit print "v1", timeit.Timer('v1()', 'from __main__ import v1').timeit(500000) print "v2", timeit.Timer('v2()', 'from __main__ import v2').timeit(500000)  > output v1 3.73336911201  > output v2 3.44717001915 
like image 161
ChristopheD Avatar answered Sep 19 '22 17:09

ChristopheD


efficient as in fewer lines of code?

(xval,yval,zval) = [int(s) for s in file.split('-')] 
like image 28
Bartosz Radaczyński Avatar answered Sep 18 '22 17:09

Bartosz Radaczyński