python map函数作用于一串数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12702470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:39:04  来源:igfitidea点击:

python map function acting on a string of numbers

pythonstringmap

提问by acs

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

我一直在玩 Python 中的 map 函数,我正在寻找一些帮助来理解以下行为:

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

给你[1, 2, 3, 4, 5]。显然是int(foo)吐了出来12345。那么究竟发生了什么?由于字符串可以按字符迭代,上面两行是否与

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"?

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

Thanks a lot!

非常感谢!

采纳答案by Ashwini Chaudhary

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

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

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:

随着lambda,map()变慢:

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 3x 中map()返回一个映射对象,即一个迭代器

回答by inspectorG4dget

mapcan be thought of to work like this:

map可以被认为是这样工作的:

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

Basically, it returns a list Lsuch that the ith element of Lis the result of computing funcon the ith element of your iterable.

基本上,它返回一个列表L,其中的第 i 个元素L是对func可迭代对象的第 i 个元素进行计算的结果。

So, with intand a string of ints, in each iteration of the for loop, the element is a specific character, which when given to intcomes back as an actual int. The result of calling mapon such a string is a list, whose elements correspond to the inted values of the corresponding character in the string.

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

So yes, if L = "12345", then map(int, L)is synonymous with [int(x) for x in L]

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

Hope this helps

希望这可以帮助

回答by Perkins

Yes, there is a huge difference behind the scenes. If you print(map)you'll see it is a builtin. A builtin function executes faster than one written in python or than most that are based off of how the language is parsed, map uses the fast iter method, a list comprehension does not. Other that there is no difference.

是的,幕后有很大的不同。如果你print(map)会看到它是一个内置的。内置函数的执行速度比用 Python 编写的函数快,或者比大多数基于语言解析方式的函数执行得快,map 使用快速迭代方法,而列表推导则没有。其他没有什么区别。

map(int, '1'*1000000)

vs.

对比

[int(i) for i in '1'*1000000]

Using CPython, and the unix time program, map completes in ~3 seconds, the list comprehension in ~5.

使用 CPython 和 unix time 程序,映射在 ~3 秒内完成,列表理解在 ~5 秒内完成。

Oh, one thing to note, this only pertains when the function passed to map is written in C.

哦,要注意一件事,这仅适用于传递给 map 的函数是用 C 编写的。

回答by Burhan Khalid

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

将函数应用于可迭代的每个项目并返回结果列表。

From the documentation for map

文档中map

int()attemptsto convert what is passed into an integer and will raise a ValueErrorif you try something silly, like this:

int()尝试将传递的内容转换为整数,ValueError如果您尝试一些愚蠢的操作,则会引发 a ,如下所示:

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

map()will return a list, which has the return value of the function that you ask it to call for any iterable. If your function returns nothing, then you'll get a list of Nones, like this:

map()将返回一个列表,其中包含您要求它为任何可迭代对象调用的函数的返回值。如果您的函数不返回任何内容,那么您将获得一个Nones列表,如下所示:

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

It is the short and efficientway to do something like this:

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

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

回答by root

foo="12345"

In [507]: dis.dis('map(int,foo)')
          0 <109>           28769
          3 STORE_SLICE+0  
          4 LOAD_ATTR       29806 (29806)
          7 <44>           
          8 BUILD_TUPLE     28527
         11 STORE_SLICE+1  

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

dis.dis('map(int,foo)')
          0 <109>           28769
          3 STORE_SLICE+0  
          4 LOAD_ATTR       29806 (29806)
          7 <44>           
          8 BUILD_TUPLE     28527
         11 STORE_SLICE+1  
dis.dis('[int(x) for x in foo]')
          0 DELETE_NAME     28265 (28265)
          3 LOAD_GLOBAL     30760 (30760)
          6 STORE_SLICE+1  
          7 SLICE+2        
          8 BUILD_TUPLE     29295
         11 SLICE+2        
         12 SETUP_LOOP      26912 (to 26927)
         15 JUMP_FORWARD    26144 (to 26162)
         18 JUMP_IF_FALSE   23919 (to 23940)

And timing:

和时间:

In [512]: timeit map(int,foo)
100000 loops, best of 3: 6.89 us per loop

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

In [514]: timeit mymap(int,foo)
100000 loops, best of 3: 8.29 us per loop

In [515]: timeit [int(x) for x in foo]
100000 loops, best of 3: 7.5 us per loop

回答by John La Rooy

"More efficient" is a can of worms. On this computer, it's faster to use map with CPython, but the list comprehension is faster for pypy

“更高效”是一罐蠕虫。在这台计算机上,使用 map 和CPython更快,但列表理解对于pypy更快

$ python -mtimeit 'map(int,"1234567890")'
100000 loops, best of 3: 8.05 usec per loop
$ python -mtimeit '[int(x) for x in "1234567890"]'
100000 loops, best of 3: 9.33 usec per loop
$ pypy -mtimeit 'map(int,"1234567890")'
1000000 loops, best of 3: 1.18 usec per loop
$ pypy -mtimeit '[int(x) for x in "1234567890"]'
1000000 loops, best of 3: 0.938 usec per loop

Python3 shows map()to be faster even with the extra call to list()that is required

map()即使list()需要额外的调用,Python3 也显示出更快的速度

$ python3 -mtimeit 'list(map(int,"1234567890"))'
100000 loops, best of 3: 11.8 usec per loop
$ python3 -mtimeit  '[int(x) for x in "1234567890"]'
100000 loops, best of 3: 13.6 usec per loop