Asw*_*esh 8 python map raw-input
虽然我非常喜欢python,但是当我需要在同一行中获得多个整数输入时,我更喜欢C/C++.如果我使用python,我使用:
a = map(int, raw_input().split())
Run Code Online (Sandbox Code Playgroud)
这是唯一的方式还是有任何pythonic方式来做到这一点?考虑到时间,这会花费多少?
小智 7
直观和pythonic:
a = [int(i) for i in raw_input().split()]
Run Code Online (Sandbox Code Playgroud)
在这里查看这个讨论:Python List Comprehension Vs. 地图
如果您使用带有内置函数的地图,那么它可能比 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
Run Code Online (Sandbox Code Playgroud)
具有用户定义的功能:
>>> 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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
来自Python 性能提示页面:
唯一的限制是map的“循环体”必须是函数调用。除了列表推导式的语法优势之外,它们通常与等效使用映射一样快或更快。