Умножение всех элементов массива python

Как перемножить числа в списке?

Раньше можно было использвать reduce(). Сейчас тоже можно, но эту функцию вынесли в отдельный модуль, так что строго говоря, считая импорт, получается две строчки:

import functools print (functools.reduce(lambda a, b : a * b, lst)) 
import numpy as np result = np.prod(np.array(mylist)) 
from functools import reduce # Функция для свёрки последовательности from operator import mul # Функция, перемножающая 2 числа spisok = [16, 15, 9, 14, 13] # Исходный список result = reduce(mul, spisok) # /\ Список для свёртки # /\ Используем умножение # /\ Сворачиваем контейнер 
let num = Number(prompt()) let lis = [] let mult = [] while (num) < num = Number(prompt()) lis.append(num) >var m = 1 for (let n = 0; n

Все ответы здесь отстали от современности. Как насчет python-3.8 и выше?

import math math.prod([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) 

Это пожалуй самое простое и стандартное решение ИМХО.

d = [1, 2, 3, 4, 5] print(eval(str(d)[1:-1].replace(',', '*'))) 

Если очень захотеть, то можно и в одну строчку записать, но так конечно делать не стоит , например перемножить ‘2 3 4 5’ = 120

print(list(map(lambda s, t=[1]: [t.append(i*t[-1]) for i in map(int, s.split())][0] or t[-1], ['2 3 4 5']))[0]) # 120 

Я приведу не очень практичное но красивое решение в одну строку. Оно не использует eval , побочные эффекты при работе со списком или именованные функции.

Если именованные функции разрешены, то решение может выглядеть так:

def p(a): if a: return a[0] * p(a[1:]) return 1 print(p([1, 2, 3, 4, 5])) 

Нам оно не подходит, так именованная функция требует минимум две строки для определения и вызова. Лямбду можно определить и вызвать в одной строке, но есть трудность в создании рекурсивной лямбды. Синтаксис Python разрешает такой трюк:

p = (lambda a: a[0] * p(a[1:]) if a else 1); print(p([1, 2, 3, 4, 5])) 

Это именно трюк с глобальной переменной и двумя операторами в одной строке. А можно обойтись без глобальной переменной вообще. На первый взгляд этого не может быть так как имя нужно чтобы сделать рекурсивный вызов. Но функцию можно передать как аргумент в саму себя:

p = lambda f, a: a[0] * f(f, a[1:]) if a else 1 print(p(p, [1, 2, 3, 4, 5])) 

Кажется мы ничего не выиграли: всё равно два оператора и глобальная переменная p . Однако сделан очень важный шаг — тело лямбды не использует глобальные переменные. Глобальная переменная используется в операторе print . Избавимся от неё:

p = lambda f, a: a[0] * f(f, a[1:]) if a else 1 y = lambda f, a: f(f, a) print(y(p, [1, 2, 3, 4, 5])) 

Стало только хуже: три строки и две глобальные переменные. Зато каждая глобальная переменная задействована только один раз. Делаем подстановку:

print((lambda f, a: f(f, a))(lambda f, a: a[0] * f(f, a[1:]) if a else 1, [1, 2, 3, 4, 5])) 

Читается тяжело, но задача решена в одну строку без глобальных имён и волшебных вызовов eval .

Читайте также:  Javascript return new class

P.S. Читайте Fixed-point combinator чтобы узнать откуда пошло это решение.

P.P.S. И есть очаровательное утверждение: программу любой сложность можно записать в функциональном стиле не определив ни одной глобальной переменной, включая имена функций.

P.P.P.S. Не пытайтесь повторить это дома.

Источник

Умножение всех элементов массива python

Last updated: Dec 17, 2022
Reading time · 7 min

banner

# Table of Contents

# Multiply each element in a list by a number in Python

To multiply each element in a list by a number:

  1. Use a list comprehension to iterate over the list.
  2. On each iteration, multiply the current element by the number.
  3. The new list will contain the multiplication results.
Copied!
# ✅ Multiply each element in a list by a number import math my_list = [2, 4, 6] result = [item * 10 for item in my_list] print(result) # 👉️ [20, 40, 60] # ------------------------------------------ # ✅ Multiply all elements in a list my_list = [2, 4, 6] result = math.prod(my_list) print(result) # 👉️ 48

multiply each element in list by number

We used a list comprehension to iterate over the list and multiplied each list item by 10 .

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

On each iteration, we multiply the current list item by the specified number and return the result.

Alternatively, you can use a simple for loop.

# Multiply each element in a list by a number using a for loop

This is a four-step process:

  1. Declare a new variable that stores an empty list.
  2. Use a for loop to iterate over the original list.
  3. On each iteration, multiply the current list item by the number.
  4. Append the result to the new list.
Copied!
my_list = [2, 4, 6] result = [] for item in my_list: result.append(item * 10) print(result) # 👉️ [20, 40, 60]

multiply each element in list by number using for loop

The for loop works in a very similar way to the list comprehension, but instead of returning the list items directly, we append them to a new list.

# Multiply each element in a list by a number using map()

You can also use the map() function to multiply each element in a list.

Copied!
my_list = [2, 4, 6] result = list(map(lambda item: item * 10, my_list)) print(result) # 👉️ [20, 40, 60]

multiply each element in list by number using map

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

The lambda function we passed to map gets called with each item in the list, multiplies the item by 10 and returns the result.

The last step is to use the list() class to convert the map object to a list .

# Multiply each element in a list by a number using NumPy

If you work with NumPy arrays, you can directly use the multiplication operator on the array to multiply each of its elements by a number.

Copied!
import numpy as np arr = np.array([2, 4, 6]) result = arr * 10 print(result) # 👉️ [20 40 60]

multiply each element in list by number using numpy

Multiplying a NumPy array by a number effectively multiplies each element in the array by the specified number.

Читайте также:  Строка ввода html css

Note that this only works with NumPy arrays. If you multiply a python list by a number, it gets repeated N times.

Copied!
print([2, 4, 6] * 2) # 👉️ [2, 4, 6, 2, 4, 6]

Multiplying a Python list by N returns a new list containing the elements of the original list repeated N times.

# Multiply all elements in a List in Python

If you need to multiply all elements in a list, use the math.prod() function.

The math.prod() method calculates the product of all the elements in the provided iterable.

Copied!
import math my_list = [2, 3, 5] result = math.prod(my_list) print(result) # 👉️ 30

multiply all elements in list

Make sure to import the math module at the top.

We used the math.prod method to multiply all the elements in a list.

The math.prod method calculates the product of all the elements in the provided iterable.

Copied!
import math my_list = [5, 5, 5] result = math.prod(my_list) print(result) # 👉️ 125

The method takes the following 2 arguments:

Name Description
iterable An iterable whose elements to calculate the product of
start The start value for the product (defaults to 1 )

If the iterable is empty, the start value is returned.

Alternatively, you can use the reduce() function.

# Multiply all elements in a List using reduce()

This is a two-step process:

  1. Pass a lambda function and the list to the reduce() function.
  2. The lambda function should take the accumulator and the current value and should return the multiplication of the two.
Copied!
from functools import reduce my_list = [2, 3, 5] result = reduce(lambda x, y: x * y, my_list) print(result) # 👉️ 30

The reduce function takes the following 3 parameters:

Name Description
function A function that takes 2 parameters — the accumulated value and a value from the iterable.
iterable Each element in the iterable will get passed as an argument to the function.
initializer An optional initializer value that is placed before the items of the iterable in the calculation.

The lambda function gets called with the accumulated value and the value of the current iteration and multiplies them.

If we provide a value for the initializer argument, it is placed before the items of the iterable in the calculation.

Copied!
from functools import reduce my_list = [2, 3, 5] def do_math(acc, curr): print(acc) # 👉️ is 10 on first iteration return acc * curr result = reduce(do_math, my_list, 10) print(result) # 👉️ 300

We passed 10 for the initializer argument, so the value of the accumulator will be 10 on the first iteration.

The value of the accumulator would get set to the first element in the iterable if we didn’t pass a value for the initializer .

If the iterable is empty and the initializer is provided, the initializer is returned.

If the initializer is not provided and the iterable contains only 1 item, the first item is returned.

Copied!
from functools import reduce my_list = [2] result = reduce(lambda acc, curr: acc * curr, my_list) print(result) # 👉️ 2

# Multiply all elements in a List using a for loop

You can also use a for loop to multiply all elements in a list.

Copied!
my_list = [2, 3, 5] result = 1 for item in my_list: result = result * item print(result) # 👉️ 30

On each iteration of the for loop, we multiply the result variable by the current list item and reassign it to the result.

Читайте также:  Getting filename without extension java

# Multiply two lists element-wise in Python

To multiply two lists element-wise:

  1. Use the zip function to get an iterable of tuples with the corresponding items.
  2. Use a list comprehension to iterate over the iterable.
  3. On each iteration, multiply the values in the current tuple.
Copied!
list_1 = [1, 2, 3] list_2 = [4, 5, 6] # 👇️ [(1, 4), (2, 5), (3, 6)] print(list(zip(list_1, list_2))) result = [x * y for x, y in zip(list_1, list_2)] print(result) # 👉️ [4, 10, 18]

The zip function iterates over several iterables in parallel and produces tuples with an item from each iterable.

Copied!
list_1 = [1, 2, 3] list_2 = [4, 5, 6] # 👇️ [(1, 4), (2, 5), (3, 6)] print(list(zip(list_1, list_2)))

You can imagine that the zip() function iterates over the lists, taking 1 item from each.

The first tuple in the list consists of the elements in each list with an index of 0 , the second tuple consists of the elements in each list that have an index of 1 , etc.

The last step is to use a list comprehension to iterate over the zip object and multiply the values in each tuple.

Copied!
list_1 = [1, 2, 3] list_2 = [4, 5, 6] # 👇️ [(1, 4), (2, 5), (3, 6)] print(list(zip(list_1, list_2))) result = [x * y for x, y in zip(list_1, list_2)] print(result) # 👉️ [4, 10, 18]

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

On each iteration, we unpack the values from the tuple and use the multiplication * operator to multiply them.

Copied!
a, b = (2, 5) print(a * b) # 👉️ 10

# Multiplying more than two lists element-wise

You can also use this approach to multiply more than two lists element-wise.

Copied!
list_1 = [1, 2, 3] list_2 = [4, 5, 6] list_3 = [7, 8, 9] # 👇️ [(1, 4, 7), (2, 5, 8), (3, 6, 9)] print(list(zip(list_1, list_2, list_3))) result = [x * y * z for x, y, z in zip(list_1, list_2, list_3)] print(result) # 👉️ [28, 80, 162]

Alternatively, you can use the map() function.

# Multiply two lists element-wise using map()

This is a two-step process:

  1. Use the map() function to call the mul() function with the two lists.
  2. Use the list() class to convert the map object to a list.
Copied!
from operator import mul list_1 = [1, 2, 3] list_2 = [4, 5, 6] result = list(map(mul, list_1, list_2)) print(result) # 👉️ [4, 10, 18]

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

The mul function from the operator module is the same as a * b .

You can imagine that map calls the mul function with each item of the two iterables (e.g. items at index 0 , then 1 , etc).

The map function returns a map object, so we had to use the list() class to convert the result to a list.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью