How do I multiply each element in a list by a number?

后端 未结 8 1143
囚心锁ツ
囚心锁ツ 2020-11-27 04:29

I have a list:

my_list = [1, 2, 3, 4, 5]

How can I multiply each element in my_list by 5? The output should be:



        
相关标签:
8条回答
  • 2020-11-27 05:00
    from functools import partial as p
    from operator import mul
    map(p(mul,5),my_list)
    

    is one way you could do it ... your teacher probably knows a much less complicated way that was probably covered in class

    0 讨论(0)
  • 2020-11-27 05:05

    Best way is to use list comprehension:

    def map_to_list(my_list, n):
    # multiply every value in my_list by n
    # Use list comprehension!
        my_new_list = [i * n for i in my_list]
        return my_new_list
    # To test:
    print(map_to_list([1,2,3], -1))
    

    Returns: [-1, -2, -3]

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