Python 使用 map(int, raw_input().split())

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17121706/
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-19 00:31:47  来源:igfitidea点击:

using map(int, raw_input().split())

pythonmapraw-input

提问by Aswin Murugesh

Though I like python very much, When I need to get multiple integer inputs in the same line, I prefer C/C++. If I use python, I use:

虽然我非常喜欢python,但是当我需要在同一行中获得多个整数输入时,我更喜欢C/C++。如果我使用 python,我使用:

a = map(int, raw_input().split())

Is this the only way or is there any pythonic way to do it? And does this cost much as far as time is considered?

这是唯一的方法还是有任何pythonic方法来做到这一点?就时间而言,这是否成本高?

采纳答案by Ashwini Chaudhary

If you're using map with built-in function then it can be slightly faster than LC:

如果您使用带有内置函数的 map,那么它可能比 LC 稍快:

>>> strs = " ".join(str(x) for x in xrange(10**5))
>>> %timeit [int(x) for x in strs.split()]
1 loops, best of 3: 111 ms per loop
>>> %timeit map(int, strs.split())
1 loops, best of 3: 105 ms per loop

With user-defined function:

使用用户定义函数:

>>> def func(x):
...     return int(x)

>>> %timeit map(func, strs.split())
1 loops, best of 3: 129 ms per loop
>>> %timeit [func(x) for x in strs.split()]
1 loops, best of 3: 128 ms per loop

Python 3.3.1 comparisons:

Python 3.3.1 比较:

>>> strs = " ".join([str(x) for x in range(10**5)])
>>> %timeit list(map(int, strs.split()))
10 loops, best of 3: 59 ms per loop
>>> %timeit [int(x) for x in strs.split()]
10 loops, best of 3: 79.2 ms per loop

>>> def func(x):                         
    return int(x)
... 
>>> %timeit list(map(func, strs.split()))
10 loops, best of 3: 94.6 ms per loop
>>> %timeit [func(x) for x in strs.split()]
1 loops, best of 3: 92 ms per loop

From Python performance tipspage:

来自Python 性能提示页面:

The only restriction is that the "loop body" of map must be a function call. Besides the syntactic benefit of list comprehensions, they are often as fast or faster than equivalent use of map.

唯一的限制是 map 的“循环体”必须是函数调用。除了列表推导式的语法优势外,它们通常与 map 的等效使用一样快或更快。

回答by phil-ociraptor

List comprehensions!

列举理解!

Intuitive and pythonic:

直观和pythonic:

a = [int(i) for i in raw_input().split()]

Check out this discussion here: Python List Comprehension Vs. Map

在此处查看此讨论:Python List Comprehension Vs。地图

回答by Tanay Agrawal

You can use this:

你可以使用这个:

s = raw_input().split()
s = [int(i) for i in s]

回答by Muhammad bilal

def pairs(a,k):
  answer = 0
  s = set(a)
  for v in s:
    if v+k in s:
        answer += 1

  return answer

n, k = map(int, raw_input().split())
b = map(int, raw_input().split())
print pairs(b, k)