python map函数作用于一串数字 [英] python map function acting on a string of numbers

查看:170
本文介绍了python map函数作用于一串数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在Python中使用map功能,我正在寻找一些帮助来理解以下行为:

  foo =12345
print map(int,foo)

code> [1,2,3,4,5] 。显然 int(foo)吐出 12345 。那究竟发生了什么呢?由于字符串是以字符进行迭代的,所以上述两行与

  print [int(x)for x in foo] 

我知道他们会输出相同的结果,但幕后有什么不同吗?比另一个更有效率还是更好?还有一个pythonic?



非常感谢!

解决方案

map()在某些情况下可能会比使用列表解析稍微快一点,在某些情况下,地图比列表推导要慢。



当使用内置函数时:

  python -mtimeit -s'xs = xrange(1000) map(int,1234567890)'
10000循环,最佳3:18.3 usec每循环

python -mtimeit -s'xs = xrange(1000)''[int(x )for x in1234567890]'
100000循环,最好为3:20 usec每循环

lambda map()变慢:



$ {code> python -mtimeit -s'xs = xrange(1000)''[x * 10 for x in1234567890]'
100000个循环,最好的3:6.11 usec per loop

python -mtimeit -s'xs = xrange(1000)''map(lambda x:x * 10,1234567890)'
100000循环,最好的3:每循环11.2 usec

但是,在python 3x map()返回地图对象,即迭代器


I've been playing around with the map function in Python and I was looking for some help in understanding the following behaviour:

foo="12345"
print map(int,foo)

gives you [1, 2, 3, 4, 5]. Obviously int(foo) spits out 12345. So what exactly is happening? Since strings are iterable by character, would the above two lines be synonymous with

print [int(x) for x in foo]

I know they will output the same result but is there anything different going on behind the scenes? Is one more efficient or better than another? Is one more "pythonic"?

Thanks a lot!

解决方案

map() may be somewhat faster than using list comprehension in some cases and in some cases map is slower than list comprehensions.

when using a built-in function:

python -mtimeit -s'xs=xrange(1000)' 'map(int,"1234567890")'
10000 loops, best of 3: 18.3 usec per loop

python -mtimeit -s'xs=xrange(1000)' '[int(x) for x in "1234567890"]'
100000 loops, best of 3: 20 usec per loop

with lambda,map() becomes slow:

python -mtimeit -s'xs=xrange(1000)' '[x*10 for x in "1234567890"]'
100000 loops, best of 3: 6.11 usec per loop

python -mtimeit -s'xs=xrange(1000)' 'map(lambda x:x*10,"1234567890")'
100000 loops, best of 3: 11.2 usec per loop

But, in python 3x map() returns a map object, i.e. an iterator

这篇关于python map函数作用于一串数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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