1

您可以像这样生成三角形数字

limit = 10
triangle_nums = []
num = 0

for i in range(1, limit + 1):
    num += i
    triangle_nums.append(num)
print(triangle_nums)

output==================
[1, 3, 6, 10, 15, 21, 28, 36, 45, 55]

但是有没有更好的方法在一个班轮中使用更实用的方法来做到这一点?

4

1 回答 1

3

是的,使用内置的itertools.accumulate

>>> from itertools import accumulate
>>> limit = 10
>>> list(accumulate(range(1, limit+1)))
[1, 3, 6, 10, 15, 21, 28, 36, 45, 55]

注意,itertools.accumulate可以进行任何二元运算,但默认为加法,

>>> list(accumulate(range(1, limit+1))) # defaults to addition
[1, 3, 6, 10, 15, 21, 28, 36, 45, 55]
>>> list(accumulate(range(1, limit+1), lambda x,y : x + y)) # you could pass it as an argument
[1, 3, 6, 10, 15, 21, 28, 36, 45, 55]
but you could use multiplication as an example:


>>> list(accumulate(range(1, limit+1), lambda x, y : x*y))
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
于 2019-03-01T01:53:14.370 回答