作用于一串数字的python map函数

2024-04-29 10:28:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在使用Python中的map函数,希望能帮助理解以下行为:

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

给你[1, 2, 3, 4, 5]。显然int(foo)会吐出12345。那么到底发生了什么?由于字符串是由字符组成的,上面两行是否是

print [int(x) for x in foo]

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

非常感谢!


Tags: 函数字符串inmapforfoo字符int
3条回答

map()在某些情况下可能比使用列表理解快一些,在某些情况下,map比列表理解慢一些。

使用内置函数时:

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

随着lambdamap()变慢:

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

但是,在python 3x中{}返回一个映射对象,即迭代器

Apply function to every item of iterable and return a list of the results.

来自the documentation for ^{}

int()尝试将传递的内容转换为整数,并将引发一个ValueError如果您尝试一些愚蠢的操作,例如:

>>> int('Hello')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'Hello'

map()将返回一个列表,该列表具有您要求它调用任何iterable的函数的返回值。如果您的函数不返回任何内容,那么您将得到一个Nones的列表,如下所示:

>>> def silly(x):
...   pass
...
>>> map(silly,'Hello')
[None, None, None, None, None]

这是做这种事情的短而有效的方法:

   def verbose_map(some_function,something):
       results = []
       for i in something:
          results.append(some_function(i))
       return results

map可以这样工作:

def map(func, iterable):
    answer = []
    for elem in iterable:
        answer.append(func(elem))
    return answer

基本上,它返回一个列表L,使得L的第i个元素是计算iterable的第i个元素func的结果。

因此,对于int和一个ints字符串,在for循环的每个迭代中,元素都是一个特定的字符,当给定给int时,它返回为一个实际的int。对这样的字符串调用map的结果是一个列表,其元素对应于字符串中相应字符的inted值。

所以是的,如果L = "12345",那么map(int, L)就是[int(x) for x in L]的同义词

希望这有帮助

相关问题 更多 >