How to perform element-wise multiplication of two lists?
Use a list comprehension mixed with zip()
:.
[a*b for a,b in zip(lista,listb)]
Multiply two list of different sizes element wise without using libraries in python
For problems with iteration, I suggest anyone to check Loop Like A Native by Ned Batchelder and Looping like a Pro by David Baumgold
Option 1
If you want to multiply them as far as the shortest list goes, zip
is your friend:
multiples = [a * b for a, b in zip (x, squares)]
Option 2
If you want a matrix with the product, then you can do it like this
result = [
[a * b for a in x]
for b in squares
]
Pairwise multiplication of elements between two lists
You're close. What you really want is two for loops so you can compare each value in one list against all of the values in the second list. e.g.
def multiply_lists(list1, list2):
for i in range(len(list1)):
for j in range(len(list2)):
products.append(list1[i] * list2[j])
return products
You also don't need a range
col, you can directly iterate over the items of each list:
def multiply_lists(list1, list2):
for i in list1:
for j in list2:
products.append(i * j)
return products
And you could also do this as a comprehension:
def multiply_lists(list1, list2):
return [i * j for i in list1 for j in list2]
Element-wise multiplication of two lists in Tcl
A two-list lmap
is perfect for this:
set a {1 2 3 4 5}
set b {1 2 3 4 5}
set result [lmap x $a y $b {expr {$x * $y}}]
If you're on Tcl 8.5 (or older) use this instead:
set a {1 2 3 4 5}
set b {1 2 3 4 5}
set result {}
foreach x $a y $b {
lappend result [expr {$x * $y}]
}
The multi-list form of foreach
has been supported for a very long time indeed.
Element wise multiplication of two lists
We can mget
to get the values of the objects in a list
for both 'sepalvar' and 'petalvar', and use Map
to do the *
for corresponding elements, and assign (:=
) it to two new columns
library(data.table)
setDT(iris)[, c('multlength', 'multwidth')
:= Map(`*`, mget(sepalvar), mget(petalvar))]
-output
head(iris)
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species multlength multwidth
#1: 5.1 3.5 1.4 0.2 setosa 7.14 0.70
#2: 4.9 3.0 1.4 0.2 setosa 6.86 0.60
#3: 4.7 3.2 1.3 0.2 setosa 6.11 0.64
#4: 4.6 3.1 1.5 0.2 setosa 6.90 0.62
#5: 5.0 3.6 1.4 0.2 setosa 7.00 0.72
#6: 5.4 3.9 1.7 0.4 setosa 9.18 1.56
Or another option is to use .SD
setDT(iris)[, c('multlength', 'multwidth') :=
.SD[, ..sepalvar] * .SD[, ..petalvar]]
Element wise multiplication of two list that are tf.Tensor in tensorflow
This is called the outer product of two tensors. It's easy to compute by taking advantage of Tensorflow's broadcasting rules:
import numpy as np
import tensorflow as tf
t = tf.constant([[0, 1],[2, 3]])
a = np.array([0, 1, 2])
# (2,2) x (3,1,1) produces the desired shape of (3,2,2)
result = t * a.reshape((-1, 1, 1))
# Alternatively: result = t * a[:, np.newaxis, np.newaxis]
print(result)
results in
<tf.Tensor: shape=(3, 2, 2), dtype=int32, numpy=
array([[[0, 0],
[0, 0]],
[[0, 1],
[2, 3]],
[[0, 2],
[4, 6]]], dtype=int32)>
Element-wise multiplication of a series of two lists from separate Pandas Dataframe Series in Python
Your code is almost there. Mostly, you need to pass axis=1
to apply:
df["new"] = df.apply(lambda x: list(a*b for a,b in zip(x['List A'], x['List B'])), axis=1)
print(df)
The output is:
ref List A List B new
0 A [0, 1, 2] [0, 1, 2] [0, 1, 4]
1 B [2, 3, 4] [2, 3, 4] [4, 9, 16]
2 C [3, 4, 5] [3, 4, 5] [9, 16, 25]
3 D [4, 5, 6] [4, 5, 6] [16, 25, 36]
Element-wise product of two 2-D lists
You can zip
the two lists in a list comprehension, then further zip
the resulting sublists and then finally multiply the items:
list2 = [[5,2,9,3,7],[1,3,5,2,2]]
list1 = [[2,3,5,6,7],[5,2,9,3,7]]
result = [[a*b for a, b in zip(i, j)] for i, j in zip(list1, list2)]
print(result)
# [[10, 6, 45, 18, 49], [5, 6, 45, 6, 14]]
Should in case the lists/sublists do not have the same number of elements, itertools.izip_longest
can be used to generate fill values such as an empty sublist for the smaller list, or 0 for the shorter sublist:
from itertools import izip_longest
list1 = [[2,3,5,6]]
list2 = [[5,2,9,3,7],[1,3,5,2,2]]
result = [[a*b for a, b in izip_longest(i, j, fillvalue=0)]
for i, j in izip_longest(list1, list2, fillvalue=[])]
print(result)
# [[10, 6, 45, 18, 0], [0, 0, 0, 0, 0]]
You may change the inner fillvalue
from 0 to 1 to return the elements in the longer sublists as is, instead of a homogeneous 0.
Reference:
List comprehensions
Python: How do I multiply and sum elements across two lists (without using a library)?
You can play with python built-in functions and a nested list comprehension :
>>> [[sum(t*k for t,k in zip(i,j)) for j in m2] for i in m1]
[[31, 19], [85, 55]]
You can also use itertools.product
to find the products between sub-lists :
>>> from itertools import product
>>> [sum(t*k for t,k in zip(i,j)) for i,j in product(m1,m2)]
[31, 19, 85, 55]
Related Topics
What Is Ruby Equivalent of Python's 'S= "Hello, %S. Where Is %S" % ("John","Mary")'
Benchmarks: Does Python Have a Faster Way of Walking a Network Folder
Is There a Static Analysis Tool for Python, Ruby, SQL, Cobol, Perl, and Pl/Sql
Ruby Methods Equivalent of "If a in List" in Python
Bloomberg Server API and Ruby/Python
Pyobjc VS Rubycocoa for MAC Development: Which Is More Mature
Create Static Graphics Files (Png, Gif, Jpg) Using Ruby or Python
Python's Equivalent for Ruby's Define_Method
Python Equivalent of Ruby's .Select
How to Decrypt Aws Ruby Client-Side Encryption in Python
Using Perl, Python, or Ruby, How to Write a Program to "Click" on the Screen at Scheduled Time
Xcode 3.2 Ruby and Python Templates
What Does Blazeds Livecycle Data Services Do, That Something Like Pyamf or Rubyamf Not Do
Separate a Row of Strings into Separate Rows
Is There a Python Equivalent for Rspec to Do Tdd