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

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]


但是有没有更好的方法可以使用功能更强的方法在一个衬套中做到这一点?

最佳答案

是的,使用内置的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]

10-06 09:05