l2=[[13,11,9],[7,5,3],[1]]
I want to multiply each sublist in list l2
with a constant number i.e 13*1,11*1,9*1 and 7*2,5*2,3*2 and 1*3 and the final result would be 13,11,9 and 14,10,6 and 3.
l2=[[13,11,9],[7,5,3],[1]]
I want to multiply each sublist in list l2
with a constant number i.e 13*1,11*1,9*1 and 7*2,5*2,3*2 and 1*3 and the final result would be 13,11,9 and 14,10,6 and 3.
Using enumerate
Ex:
l2=[[13,11,9],[7,5,3],[1]]
print([[j*i for j in v] for i, v in enumerate(l2, 1)])
Output:
[[13, 11, 9], [14, 10, 6], [3]]
You can leverage enumerate
here:
l2 = [[13,11,9],[7,5,3],[1]]
l3 = [[x * (idx + 1) for x in sublist] for idx, sublist in enumerate(l2)]
print(l3)
This yields
[[13, 11, 9], [14, 10, 6], [3]]
Try this:
l2=[[13,11,9],[7,5,3],[1]]
counter = 1
for i in range(len(l2)):
for j in range(len(l2[i])):
l2[i][j] *= counter
counter += 1
print(l2)
Is it always the first sublist is 1, the 2nd is two, etc?
for i in range(0, len(l2)):
i += 1
print(f'{l2[i-1]} times {i}')
print(list(map(lambda x: x*i, l2[i-1])))
One liner with map
and enumerate
[map((idx).__mul__, sublist) for idx,sublist in enumerate(l2,1)] #[[13, 11, 9], [14, 10, 6], [3]]
using numpy.multiply
import numpy as np
[np.multiply(sublist,[idx]).tolist() for idx,sublist in enumerate(l2,1)]
new_list = []
multiplier = 1
# passing over sublists( e.g. [13,11,9] = li) in l2
for li in l2:
# multiply all elements in sublist(li) with multiplier(in first step multiplier = 1)
# append the multiplied sublist to the new list
new_list.append([li[i]*multiplier for i in range(len(li))])
# multiplier increase by one (e.g. in second step we need to multiply elements from second sublist with multiplier = 2)
multiplier += 1
print (new_list)