How do I multiply lists together using a function?

前端 未结 6 689
孤城傲影
孤城傲影 2020-12-07 05:01

how do I multiply lists together in python using a function? This is what I have:

    list = [1, 2, 3, 4]
    def list_multiplication(list, value):
                  


        
6条回答
  •  盖世英雄少女心
    2020-12-07 05:30

    You can use a list comprehension:

    >>> t = [1, 2, 3, 4]
    >>> [i**2 for i in t]
    [1, 4, 9, 16]
    

    Note that 1*1, 2*2, etc is the same as squaring the number.


    If you need to multiply two lists, consider zip():

    >>> L1 = [1, 2, 3, 4]
    >>> L2 = [1, 2, 3, 4]
    >>> [i*j for i, j in zip(L1, L2)]
    [1, 4, 9, 16]
    

提交回复
热议问题