Raising elements of a list to a power

前端 未结 8 1956
傲寒
傲寒 2020-12-17 18:02

How can I raise the numbers in list to a certain power?

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-17 18:43

    Nobody has mentioned map and functools.partial and the accepted answer does not mention pow, but for the sake of completeness I am posting this solution:

    import functools
    bases = numbers = [1,2,3]
    power = exponent = 3
    cubed = list(map(functools.partial(pow, exponent), numbers))
    

    I would use a list comprehension myself as suggested, but I think functools.partial is a very cool function that deserves to be shared. I stole my answer from @sven-marnach here by the way.

提交回复
热议问题