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

后端 未结 8 1178
囚心锁ツ
囚心锁ツ 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 04:52

    You can just use a list comprehension:

    my_list = [1, 2, 3, 4, 5]
    my_new_list = [i * 5 for i in my_list]
    
    >>> print(my_new_list)
    [5, 10, 15, 20, 25]
    

    Note that a list comprehension is generally a more efficient way to do a for loop:

    my_new_list = []
    for i in my_list:
        my_new_list.append(i * 5)
    
    >>> print(my_new_list)
    [5, 10, 15, 20, 25]
    

    As an alternative, here is a solution using the popular Pandas package:

    import pandas as pd
    
    s = pd.Series(my_list)
    
    >>> s * 5
    0     5
    1    10
    2    15
    3    20
    4    25
    dtype: int64
    

    Or, if you just want the list:

    >>> (s * 5).tolist()
    [5, 10, 15, 20, 25]
    

提交回复
热议问题