在Python中将字符串从split函数转换为int的有效方法 [英] Efficient way to convert strings from split function to ints in Python

查看:6186
本文介绍了在Python中将字符串从split函数转换为int的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下格式的数据字符串:xpos-ypos-zoom(即8743-12083-15),我想分割并存储在变量xpos,ypos和zoom中。由于我需要对这些数字做一些计算,我想从一开始就将它们转换为整数。目前,我这样做的方式是使用以下代码:

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?

推荐答案

我的原始建议列表理解。

My original suggestion with a list comprehension.

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

编辑

高效(cpu-cyclewise)是应该总是测试的东西。
对我的Python 2.6安装的一些快速测试表明 map 可能是这里最有效的候选项(从一个值分割的字符串构建一个整数列表)。请注意,差异是如此之小,这是没有什么关系,直到你做这几百万次(它是一个被证明的瓶颈)...真的不重要...

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

这篇关于在Python中将字符串从split函数转换为int的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆