Kareltje12
Kareltje12

Reputation: 25

Multiplication of elements in list of lists

hello I am trying to multiply certain lists in a list of lists by variables.

let's say I have the following

[['', 'header1.txt', 'header2.txt', 'header3.txt', 'header4.txt'],
 ['cow', 4, 3, 2, 10],
 ['pig', 20, 4, 7, 2]]

and the following variables :

cows = 2
pigs = 4

How would I multiply the cow list by the variable cow and the pig list by the variable pig to create

[['', 'header1.txt', 'header2.txt', 'header3.txt', 'header4.txt'],
 ['cow', 8.0, 6.0, 4.0, 4.0],
 ['pig', 80.0, 16.0, 28.0, 8.0]]

It doesnt have to be floats, but this would be ideal. I tried it with something like this

matrix = [['', 'header1.txt', 'header2.txt', 'header3.txt', 'header4.txt'],
          ['cow', 4, 3, 2, 10],
          ['pig', 20, 4, 7, 2]]
cows = 2
pigs = 4
weightmatrix = []

for value in matrix:
    try:
        weightmatrix.append(matrix[1]*cows)
        weightmatrix.append(matrix[2]*pigs)
    except:
        pass
print(weightmatrix)

However for me this creates double the elements in every list, it just seems to copy and paste the list behind each other instead of multiplying the values.

Upvotes: 0

Views: 84

Answers (2)

flakes
flakes

Reputation: 23624

You need to replace each item individually in the list when you get a match. You can't just multiply the whole list.

I would also suggest putting the operations into dict for convenience.

matrix = [
    ['', 'header1.txt', 'header2.txt', 'header3.txt', 'header4.txt'],
    ['cow', 4, 3, 2, 10],
    ['pig', 20, 4, 7, 2],
]
ops = {
    'cow': 2,
    'pig': 4,
}

for row in matrix:
    if row[0] in ops:
        for i in range(1, len(row)):
            row[i] *= ops[row[0]]

Upvotes: 1

orlp
orlp

Reputation: 117681

Here's how I'd solve it:

matrix = [['', 'header1.txt', 'header2.txt', 'header3.txt', 'header4.txt'],
          ['cow', 4, 3, 2, 10],
          ['pig', 20, 4, 7, 2]]
multipliers = {
    "cow": 2,
    "pig": 4,
}

for i, row in enumerate(matrix):
    m = multipliers.get(row[0])
    if m is not None:
        matrix[i] = [row[0]] + [x * m for x in row[1:]]

Upvotes: 1

Related Questions