Raising elements of a list to a power

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

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

相关标签:
8条回答
  • 2020-12-17 18:21

    Actually your script do what you want, and that is the result (keep in mind that you are applying the power function to [1,2,3,4,5,6,7,8,9])

    ('Cubic list:', [1, 8, 27, 64, 125, 216, 343, 512, 729])

    Your problem is that you also modified the original list, due to the nature on the list type in python. If you want to keep also your original list you should pass a copy of it to your function. You can do it like this

    def main():
        numbers=[1,2,3,4,5,6,7,8,9]
        numbers3=power(numbers[:])
        print('Original list:', numbers)
        print('Cubic list:', numbers3)
    
    0 讨论(0)
  • 2020-12-17 18:27
    def turn_to_power(list, power=1): 
        return [number**power for number in list]
    

    Example:

       list = [1,2,3]
       turn_to_power(list)
    => [1, 2, 3]
       turn_to_power(list,2)
    => [1, 4, 9]
    

    UPD: you should also consider reading about pow(x,y) function of math lib: https://docs.python.org/3.4/library/math.html

    0 讨论(0)
  • 2020-12-17 18:28

    Use a list comprehension for some increased speed:

    print('Original list:', numbers)
    print('Cubic list:', [n**3 for n in numbers])
    
    0 讨论(0)
  • 2020-12-17 18:38
    print(list(map(pow,numbers,repeat(2)))
    
    0 讨论(0)
  • 2020-12-17 18:40

    Use list comprehension:

    def power(my_list):
        return [ x**3 for x in my_list ]
    

    https://docs.python.org/3.4/tutorial/datastructures.html#list-comprehensions

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题