Create list of factorials using list comprehension

前端 未结 3 1642
挽巷
挽巷 2021-01-23 11:26

I\'m trying to build a list of the first ten factorials

[1,1,2,6,24,120,720,5040,40320,362880]

using only list comprehension. Is that possible

3条回答
  •  礼貌的吻别
    2021-01-23 12:09

    Your attempt does not work because the list comprehension works element-wise, you cannot refer to lst[i-1] like that. There is a factorial function in math module, however, since you mentioned generators, you can use one like this

    def mygenerator():
        total = 1
        current = 1
        while True:
            total *= current
            yield total
            current += 1
    
    factorial = mygenerator()
    output = [next(factorial) for i in range(10)]
    

提交回复
热议问题