相关疑难解决方法(0)

当`starmap`可能优于`List Comprehension`

在回答Clunky计算增量数字之间差异的问题时,是否有更美妙的方法?,我想出了两个解决方案,一个List Comprehension和另一个使用list comprehension.

对我来说,starmapSyntax看起来更清晰,可读,更简洁,更Pythonic.但仍然List Comprehension在itertools中可用,我想知道,必须有一个理由.

我的问题是什么时候There should be one-- and preferably only one --obvious way to do it.可以优先考虑LC

注意如果它是Style的问题那么它肯定是矛盾的LC

头对头比较

可读性很重要.---starmap

它再次成为一种感知问题,但对我starmap来说更具可读性operator.要使用lambda,您需要导入multi-variable,或定义itertools或显式LC功能,然而从中进行额外导入List Comprehension.

表现 ---list comprehension

>>> 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 …
Run Code Online (Sandbox Code Playgroud)

python list-comprehension python-itertools

7
推荐指数
2
解决办法
3745
查看次数