English 中文(简体)
当“星号”比“List Comprehension”更可取时
原标题:When`starmap` could be preferred over `List Comprehension`

在回答Clunky 计算出的一组增量数字之间的差异,是否比较好? 我提出了两个解决办法,一个是List Comprehension,另一个是itertools.starmap/a>。

对我来说,<代码> 清单理解x 认为更清晰、更可读、少易懂、更富足。 但仍然作为starmap。 我很想知道的是,它完全可以采用惯用器,因此必须有这样做的理由。

我的问题是:starmap。 可在<条码>上选取。

<><>>>>> 如果是这样的话,这无疑与<编码>相矛盾。 最好只采用一种方式——。

<>Head to Head Comparative

可重新计算。 www.un.org/spanish/ecosoc

Its again a matter of perception but to me LC is more readable than starmap. To use starmap, either you need to import operator, or define lambda or some explicit multi-variable function and nevertheless extra import from itertools.

Performance<> www.un.org/spanish/ecosoc

>>> def using_star_map(nums):
    delta=starmap(sub,izip(nums[1:],nums))
    return sum(delta)/float(len(nums)-1)
>>> def using_LC(nums):
    delta=(x-y for x,y in izip(nums[1:],nums))
    return sum(delta)/float(len(nums)-1)
>>> nums=[random.randint(1,10) for _ in range(100000)]
>>> t1=Timer(stmt= using_star_map(nums) ,setup= from __main__ import nums,using_star_map;from itertools import starmap,izip )
>>> t2=Timer(stmt= using_LC(nums) ,setup= from __main__ import nums,using_LC;from itertools import izip )
>>> print "%.2f usec/pass" % (1000000 * t1.timeit(number=1000)/100000)
235.03 usec/pass
>>> print "%.2f usec/pass" % (1000000 * t2.timeit(number=1000)/100000)
181.87 usec/pass
问题回答

通常见map(>/starmap(>)在你实际上只是要求就名单上的每一项目履行一项职能的情况下最为合适。 在这种情形下,它们更清楚:

(f(x) for x in y)
map(f, y) # itertools.imap(f, y) in 2.x

(f(*x) for x in y)
starmap(f, y)

当你开始需要在<代码>lambda或filter<>/code>上投放时,你就应当改到名单上的同化者/代人表达方式,但在担任单一职务时,辛塔克斯人会感到非常友好,以表示对名单的谅解。

They are interchangeable, and where in doubt, stick to the generator expression as it s more readable in general, but in a simple case (map(int, strings), starmap(Vector, points)) using map()/starmap() can sometimes make things easier to read.

Example:

更可读的一个例子是:

from collections import namedtuple
from itertools import starmap

points = [(10, 20), (20, 10), (0, 0), (20, 20)]

Vector = namedtuple("Vector", ["x", "y"])

for vector in (Vector(*point) for point in points):
    ...

for vector in starmap(Vector, points):
    ...

www.un.org/Depts/DGACM/index_french.htm

values = ["10", "20", "0"]

for number in (int(x) for x in values):
    ...

for number in map(int, values):
    ...

Performance:

python -m timeit -s "from itertools import starmap" -s "from operator import sub" -s "numbers = zip(range(100000), range(100000))" "sum(starmap(sub, numbers))"                         
1000000 loops, best of 3: 0.258 usec per loop

python -m timeit -s "numbers = zip(range(100000), range(100000))" "sum(x-y for x, y in numbers)"                          
1000000 loops, best of 3: 0.446 usec per loop

构造<代码>改为<>。

python -m timeit -s "from itertools import starmap" -s "from collections import namedtuple" -s "numbers = zip(range(100000), reversed(range(100000)))" -s "Vector = namedtuple( Vector , [ x ,  y ])" "list(starmap(Vector, numbers))"
1000000 loops, best of 3: 0.98 usec per loop

python -m timeit -s "from collections import namedtuple" -s "numbers = zip(range(100000), reversed(range(100000)))" -s "Vector = namedtuple( Vector , [ x ,  y ])" "[Vector(*pos) for pos in numbers]"
1000000 loops, best of 3: 0.375 usec per loop

在我的测试中,我们正在谈论使用简单的功能(第lambda),star(<>star(>)比相应的发电机表达更快。 当然,除非业绩是经证明的瓶颈,否则业绩应回溯至可读性。

<代码>lambda的例例,除<代码>>operator.sub(<>外,还以<代码>lambda <>/code(<>:>:

python -m timeit -s "from itertools import starmap" -s "numbers = zip(range(100000), range(100000))" "sum(starmap(lambda x, y: x-y, numbers))" 
1000000 loops, best of 3: 0.546 usec per loop

这在很大程度上是一种风格。 选择你认为可以读取的东西。

关于“只有一种方式”的问题,Sven Marnach 敬请见。 Guido quote:

“You may think this violates TOOWTDI, but as I ve said before, that was a white lie (as well a cheeky response to Perl s slogan around 2000). Being able to express intent (to human readers) often requires choosing between multiple forms that do essentially the same thing, but look different to the reader.”

在一个业绩热点,你可能要选择最快的解决办法(我在此情况下认为是)。

On performance - starmap is slower because of its destructuring; however starmap is not necessary here:

from timeit import Timer
import random
from itertools import starmap, izip,imap
from operator import sub

def using_imap(nums):
    delta=imap(sub,nums[1:],nums[:-1])
    return sum(delta)/float(len(nums)-1)

def using_LC(nums):
    delta=(x-y for x,y in izip(nums[1:],nums))
    return sum(delta)/float(len(nums)-1)

nums=[random.randint(1,10) for _ in range(100000)]
t1=Timer(stmt= using_imap(nums) ,setup= from __main__ import nums,using_imap )
t2=Timer(stmt= using_LC(nums) ,setup= from __main__ import nums,using_LC )

在我的计算机上:

>>> print "%.2f usec/pass" % (1000000 * t1.timeit(number=1000)/100000)
172.86 usec/pass
>>> print "%.2f usec/pass" % (1000000 * t2.timeit(number=1000)/100000)
178.62 usec/pass

远距甚远,可能是因为避免了打脚/结构。

About Starmap.. Lets say you have L = [(0,1,2),(3,4,5),(6,7,8),..].

发电机自食其力

(f(a,b,c) f或a,b,c in L)

(f(*item) f或item in L) 

严酷的图象

starmap(f, L)

第三个变量是轻度和较短的。 但首先非常明显,迫使我去做事情。

Ok. 现在我想写一下更复杂的在线守则。

some_result = starmap(f_res, [starmap(f1,L1), starmap(f2,L2), starmap(f3,L3)])

This line is not obvious, but still easy to understand.. In generat或comprehansion it would look like:

some_result = (f_res(a,b,c) f或a,b,c in [(f1(a,b,c) f或a,b,c in L1), (f2(a,b,c) f或a,b,c in L2), (f3(a,b,c) f或a,b,c in L3)])

如你所看到的那样,理解得太长,不能放在一行,因为它的特性大于79个(PEP8)。 更短的变量也不好:

some_result = (f_res(*item) f或item [(f1(*item) f或item in L1), (f(*item2) f或item in L2), (f3(*item) f或item in L3)])

太多的特性。 括号太多。 太多的噪音。

www.un.org/spanish/ecosoc 因此,在一些情况下,星号是一种非常有用的工具。 各位可以撰写较易懂的较弱的法典。

<>Restrong>EDIT后添加了一些 du子试验

from timeit import timeit
print timeit("from itertools import starmap
L = [(0,1,2),(3,4,5),(6,7,8)]
t=list((max(a,b,c)f或a,b,c in L))")
print timeit("from itertools import starmap
L = [(0,1,2),(3,4,5),(6,7,8)]
t=list((max(*item)f或item in L))")
print timeit("from itertools import starmap
L = [(0,1,2),(3,4,5),(6,7,8)]
t=list(starmap(max,L))")

产出(表2.7.2)

5.23479851154
5.35265309689
4.48601346328

因此,这里的饥饿地图甚至比15%更快。





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签