user2962397
user2962397

Reputation: 405

Simple dot product of list and nested list conditioned on indices in separate list

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

Answers (2)

bharatk
bharatk

Reputation: 4315

Using list comprehension, Valid only for -

  • if x2 has a single list.
  • and 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

Julien
Julien

Reputation: 15081

Just add the final conditioning at the end?

for m in M:
    if x[m] < x2[m]:
        result[m] = None

Upvotes: 1

Related Questions