如何以功能性方式在python中生成三角数的列表?

时间:2019-03-01 01:49:05

标签: python functional-programming

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

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]

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

1 个答案:

答案 0 :(得分: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]