使用map(int,raw_input()。split())

问题描述 投票:8回答:4

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

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

这是唯一的方法还是有任何pythonic方式来做到这一点?考虑到时间,这会花费多少?

python map raw-input
4个回答
4
投票

如果您使用的是内置函数的地图,那么它可能比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

使用用户定义的功能:

>>> 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比较:

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

来自Python performance tips页面:

唯一的限制是map的“循环体”必须是函数调用。除了列表推导的句法益处之外,它们通常比等效使用map更快或更快。


7
投票

列表理解!

直观和pythonic:

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

在这里查看这个讨论:Python List Comprehension Vs. Map


0
投票

你可以用这个:

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

-1
投票
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)
© www.soinside.com 2019 - 2024. All rights reserved.