Reputation: 23
I am curious on understanding how to multiply values from one list with two other list but both list being in the same list.
For example,
a = [[2, 3, 1, 6], [1, 6, 1, 9], [1,`1, 1,2]]
and I want to get:
[[2, 18, 1, 54], [2, 3, 1, 12]],[[2, 18, 1, 54], [1, 6, 1, 18]], [[2, 3, 1, 12], [1, 6, 1, 18]]
where a[0] multiplies with the rest of the list and a[1] multiplies with the other lists and etc.
I have searched online but I don't understand it or there aren't any examples that really look at multiply or lists together in the context of nested lists.
I am sorry if it doesn't make sense, I am still pretty new with python and english isn't my first language.
Upvotes: 1
Views: 107
Reputation: 114588
You can speed up the computation by using numpy and realizing that a * b == b * a
.
First convert a
to a numpy array:
a = np.array(a)
The output will be a 3D array:
output = np.empty((a.shape[0], a.shape[0] - 1, a.shape[1]), dtype=a.dtype)
Now get the indices in a
that you want to multiply together:
r, c = np.triu_indices(a.shape[0], k=1)
Now do the multiplication:
output[r, c - 1] = a[r] * a[c]
The lower half of the matrix is just a copy of the upper, no need to multiply:
output[c, r] = output[r, c - 1]
This solution is vectorized, which means that all of the loops have been taken out of the python layer, and moved to a fast C implementation under the hood. You can see this with the operation a[r] * a[c]
, which performs all of your multiplications in a single line. The advantage of using vectorized operations is that even when your dataset becomes very large, the operations run in a reasonable amount of time.
Upvotes: 1
Reputation: 11
You can use zip for multiplying and a for
loop for accessing the elements.
a = [[2, 3, 1, 6], [1, 6, 1, 9], [1,1, 1,2]]
b = a
result = []
for i in a:
for j in b:
if(j!=i):
k = [n1 * n2 for n1,n2 in zip(i, j)]
result.append(k)
print(result)
Upvotes: 1
Reputation: 24069
You can use numpy.array
and *
like below:
import numpy as np
a = [[2, 3, 1, 6], [1, 6, 1, 9], [1,1, 1,2]]
[list(np.array(a[i])*np.array(a[j])) for i in range(len(a)) for j in range(len(a)) if i!=j]
#expand version
# out = []
# for i in range(len(a)):
# for j in range(len(a)):
# if i!=j:
# out.append(list(np.array(a[i])*np.array(a[j])))
output:
[[2, 18, 1, 54],
[2, 3, 1, 12],
[2, 18, 1, 54],
[1, 6, 1, 18],
[2, 3, 1, 12],
[1, 6, 1, 18]]
In this answer I use numpy.array
and *
like below: (numpy do this for you)
np.array([2, 3, 1, 6]) * np.array([1, 6, 1, 9])
# [2*1, 3*6, 1*1, 6*9]
Upvotes: 2
Reputation: 120559
Use itertools.permutations
.
from itertools import permutations
a = [[2, 3, 1, 6], [1, 6, 1, 9], [1, 1, 1,2]]
b = []
for l1, l2 in permutations(a, 2):
b.append([i*j for i, j in zip(l1, l2)])
# OR with comprehension
b = [[i*j for i, j in zip(l1, l2)] for l1, l2 in permutations(a, 2)]
Output:
>>> b
[[2, 18, 1, 54],
[2, 3, 1, 12],
[2, 18, 1, 54],
[1, 6, 1, 18],
[2, 3, 1, 12],
[1, 6, 1, 18]]
Upvotes: 1