Reputation: 405
Here is a simple dot product (or sum product) using a nested list and normal list.
x1 = [[1, 1, 1], [9, 9, 9]]
x2 = [2, 2, 2]
M = [0]
result = []
for x in x1:
result.append(sum(a * b for a, b in zip(x, x2)))
result
[6, 54]
However, under a condition involving the indices m specified in M, I want to potentially have some of the elements in result be None.
I want to make this comparison: for each x[m] < x2[m]
then the value appended should be None instead of the sum product.
So the desired result using the example above should be:
result = [None, 54]
...because 1 < 2 is true so None
...and 9 < 2 is false so append the sum product as you otherwise would: 54
A requirement is that the length of M can vary and may be empty.
Upvotes: 1
Views: 94
Reputation: 4315
Using list comprehension, Valid only for -
x2
has a single list.M[0]
has a single element.Ex.
x1 = [[1, 1, 1], [9, 9, 9]]
x2 = [2, 2, 2]
M = [0]
result = []
for x in x1:
# return true if x[m] less than x2[m]
is_less = [(True if x[m] < x2[m] else False) for m in M][0]
#check is_less is true then append None into result list
if is_less:
result.append(None)
else:
result.append(sum(a * b for a, b in zip(x, x2)))
print(result)
O/P:
[None, 54]
Upvotes: 0
Reputation: 15081
Just add the final conditioning at the end?
for m in M:
if x[m] < x2[m]:
result[m] = None
Upvotes: 1