Kubix
Kubix

Reputation: 79

multiply list of lists by list of lists

Does anyone know how to multiply list of list by list of list?

[[0], [0], [12, 8, 0]] by [[1], [10], [1, 100, 1]

Expected result: [[0],[0], [12,800, 0]].

When I try I always get:

TypeError: can't multiply sequence by non-int of type 'list.

Upvotes: 4

Views: 3260

Answers (4)

Rick
Rick

Reputation: 45251

List comprehensions are great, but they can get confusing, especially for a self-described beginner.

This way is (almost) equivalent to Adem Oztas' answer, except the nested list structure is preserved:

def func(L1,L2):
    result=[]
    for xi,x in enumerate(L1):
        result.append([])
        for yi,y in enumerate(x):
            result[xi].append(y*L2[xi][yi])
    return result

print(func())

The list comprehension version would be:

[[y*L2[xi][yi] for yi,y in enumerate(x)] for xi,x in enumerate(L1) ]

This preserves the nested list structure of the inputs:

[[0],[0],[12,800,0]]

The equivalent to Apero's answer, which is:

[[a*b for a,b in zip(x,y)] for x,y in zip(lst1,lst2)]

...would be this way:

def func(L1,L2):
    result=[]
    for x,y in zip(L1,L2):
        r = []
        result.append(r)
        for a,b in zip(x,y):        
            r.append(a*b)
    return result

print(func())

Both of these other answers (using list comprehensions) are better than what I have done above using loops, since this is exactly what list comprehensions were created for. But seeing it done another way can be helpful for understanding.

Upvotes: 1

DevLounge
DevLounge

Reputation: 8437

lst1 = [[0], [1,2]]
lst2 = [[1], [2,2]]
r = [a*b for x,y in zip(lst1,lst2) for a,b in zip(x,y)]

print r

Output:

[0, 2, 4]

In this example case, it works because lst1 and lst2 have the same number of sublists which also have the same number of integers items.

Upvotes: 3

Adem Öztaş
Adem Öztaş

Reputation: 21446

Another way,

>>> l1 = [[0], [0], [12, 8, 0]]
>>> l2 = [[1], [10], [1, 100, 1]]
>>> [ ix * l2[k1][k2] for k1, item in enumerate(l1) for k2,ix in enumerate(item) ]
[0, 0, 12, 800, 0]

Upvotes: 1

Pravin
Pravin

Reputation: 1147

 List<List<Integer>> output = new ArrayList<List<Integer>>();

    for(int i = 0;i<lis1.size();i++){
        List<Integer> subOutPut = new ArrayList<Integer>();
        for(int j = 0;j<lis1.get(i).size();j++){
            subOutPut.add(lis1.get(i).get(j)*lis2.get(i).get(j));
        }
        output.add(subOutPut);
    }

In java you can achieve as above

Input : [[0], [0], [12, 8, 0]] * [[0], [0], [12, 8, 0]]

Output :[[0], [0], [12, 800, 0]]

Upvotes: 0

Related Questions