如何将其转化为理解? (蟒蛇)

时间:2013-05-01 05:19:22

标签: python list-comprehension python-2.x

此函数产生前n个值的总和,第二个n值的总和......等等。

这是功能:

def collect_sum(iterable,n):
    for e in range(1,len(ite)+1):
        if e%n==0:
            yield sum(iterable[e-n:e])

for i in c_sum(range(1,21),5):
       print(i,end=' ')

这应该返回15,40,65。当我使用列表理解时,它返回0,30,40。

3 个答案:

答案 0 :(得分:2)

def collect_sum(i,n):
    return (sum(g) for (_,g ) in groupby(i,key=lambda _,c=count():floor(next(c)/n)))
for v in collect_sum(range(1,21),5):
    print(v)

产地:

15
40
65
90
>>> 

答案 1 :(得分:1)

# generator version
def collect_sum(iterable,n):
  for e in range(1,len(iterable)+1):
    if e%n==0:
      yield sum(iterable[e-n:e])

# list comprehension version
def collect_sum(iterable,n):
  return [sum(iterable[e-n:e]) for e in range(1,len(iterable)+1) if e%n==0] 

for i in collect_sum(range(1,21),5):
  print(i,end=' ')

答案 2 :(得分:0)

使用itertools.islice

In [28]: n=5

In [29]: from itertools import islice

In [30]: lis=range(1,21)

In [31]: it=iter(lis)

In [33]: [sum(islice(it,n))  for _ in xrange(len(lis)/n) ]

Out[33]: [15, 40, 65, 90]