Multiply a list of lists by a list of lists

Does anyone know how to propagate a list of a list across a list of a list?

[[0], [0], [12, 8, 0]]

on the [[1], [10], [1, 100, 1]

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

When I try, I always get:

TypeError: Cannot multiply sequence by non-int list of types.

+3


source to share


4 answers


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, this works because lst1

both lst2

have the same number of subscriptions that also have the same number of integers.

+3


source


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]

      

+1


source


The list of concepts is extensive, but they can be confusing, especially for a self-described beginner.

This path is (almost) equivalent to Adem Oztas answer, except for keeping the nested list structure:

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 look like this:

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

      

This keeps the nested structure of the input list:

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

      

Equivalent to Apero's answer:

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

      

... will be like this:

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 lists) are better than what I did above using loops, since this is exactly what lists were created for. But seeing that it's done differently can be helpful to understand.

+1


source


 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

Login: [[0], [0], [12, 8, 0]]

*[[0], [0], [12, 8, 0]]

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

0


source







All Articles