int函数使用方法python_在Python中将字符串从split函数转换为int的有效方法

1586010002-jmsa.png

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("-")]

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值