在python中求列表子集的总和
这可能非常简单,我忽略了一些东西......
我有一长串整数,在本例中代表网站的每日访问者。我想要一份新的每周访客列表。因此,我需要从原始列表中获取七组,对它们求和,然后将它们添加到新列表中。
我的解决方案看起来相当暴力,不优雅:
numweeks = len(daily) / 7
weekly = []
for x in range(numweeks):
y = x*7
weekly.append(sum(visitors[y:y+7]))
是否有更有效或更Pythonic的方法来做到这一点?
This is probably very simple and I'm overlooking something...
I have a long list of integers, in this case representing daily visitors to a website. I want a new list of weekly visitors. So I need to get groups of seven from the original list, sum them, and add them to a new list.
My solution seems pretty brute force, inelegant:
numweeks = len(daily) / 7
weekly = []
for x in range(numweeks):
y = x*7
weekly.append(sum(visitors[y:y+7]))
Is there a more efficient, or more pythonic way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
或者稍微不那么密集:
或者,使用 numpy 模块。
请注意,这要求访问者中的元素数量是 7 的倍数。还要求您安装 numpy。然而,它可能也比其他方法更有效。
或者对于 itertools 代码奖励:
Or slightly less densely:
Alternatively, using the numpy module.
Note that this requires the number of elements in visitor be a multiple of 7. It also requires that you install numpy. However, its probably also more efficient then the other approaches.
Or for itertools code bonus:
我不确定这是否是“Pythonic”,但我真的很喜欢Python的这一行东西。
血淋淋的细节:推导式
I am not sure if this is "pythonic", but I truly love this one-line stuff of python.
Gory Details: Comprehensions
使用itertools.islice:
编辑:
或者使用math.fsum:
Using itertools.islice:
Edit:
or, with math.fsum: