Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply digits in list in python

I have a list:

lst = [[7], [4, 3, 5, 8], [1, 3]]

How can I multiply each element in list by it position like this:

[[7 * 0],[4 * 0 + 3 * 1 + 5 * 2 + 8 * 3], [1 * 0 + 3 * 1]]

And print answer:

answer = [[0], [37], [3]]
like image 264
Grenkl Bens Avatar asked Apr 18 '26 06:04

Grenkl Bens


1 Answers

You can use a list comprehension with sum and enumerate:

L = [[7], [4, 3, 5, 8], [1, 3]]

res = [[sum(i*j for i, j in enumerate(sublist))] for sublist in L]

print(res)

[[0], [37], [3]]

Or if you are happy to use a 3rd party library, you can use NumPy:

import numpy as np

L = [[7], [4, 3, 5, 8], [1, 3]]

res = [np.arange(len(sublist)).dot(sublist) for sublist in L]

print(res)

[0, 37, 3]
like image 190
jpp Avatar answered Apr 20 '26 20:04

jpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!