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

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

问题描述

我有一个具有以下格式的数据字符串: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 安装的一些快速测试表明 ma​​p 可能是这里最有效的候选者(从值拆分的字符串构建整数列表).请注意,差异是如此之小,以至于在您执行数百万次之前这并不重要(并且它已被证明是瓶颈)...

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中将字符串从拆分函数转换为整数的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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