我想为不同大小的部分计算一个集合的总和:
d = (1, 2, 3, 4, 5, 6, 7, 8, 9)
sz = (2, 3, 4)
# here I expect 1+2=3, 3+4+5=12, 6+7+8+9=30
itd = iter(d)
result = tuple( sum(tuple(next(itd) for i in range(s))) for s in sz )
print("result = {}".format(result))
我想知道我想出的解决方案是否是实现我想要的最“pythonic”(优雅、可读、简洁)的方式...
特别是,我想知道是否有办法摆脱单独的迭代器“itd”,使用切片是否会更容易?
最佳答案
我会使用 itertools.islice因为您可以直接使用 sz
中的值作为每个点的步长:
>>> from itertools import islice
>>> it=iter(d)
>>> [sum(islice(it,s)) for s in sz]
[3, 12, 30]
然后您可以根据需要将其转换为元组。
iter
当然是必需的,以便在最后一个切片停止的地方单步执行元组。否则每个切片将是 d[0:s]
关于python - 如何对集合的可变大小部分求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47946521/