Home > database >  Adding to a list of list of integers
Adding to a list of list of integers

Time:11-11

I have a list x = [[2873, 5321, 5421], [2788, 5171, 5271], [2788, 5171, 5271]]. I want to add y = 400, to each of the elements in the list. The output should be z = [3273, 5721, 5821], 3188, 5571, 5671], [3188, 5571, 5671]]

I tried by using

def add(x,y): 
addlists=[(x[i]   y) for i in range(len(x))]    
return addlists
z = add(x,y) 

But that didn't work.

I've also tried

def add(x,y):
addlists = [(x[i]   [y]) for i in range(len(x))]
    return addlists
z = add(x,y) 

But that returns z = [[2873, 5321, 5421] 400, [2788, 5171, 5271] 400, [2788, 5171, 5271] 400]

CodePudding user response:

You can use list comprehensions.

>>> x = [[2873, 5321, 5421], [2788, 5171, 5271], [2788, 5171, 5271]]

>>> [[l 400 for l in lst] for lst in x]
[[3273, 5721, 5821], [3188, 5571, 5671], [3188, 5571, 5671]]

Or your code can be like this:

def add(x,y): 
    return [[l y for l in lst] for lst in x]
    

x = [[2873, 5321, 5421], [2788, 5171, 5271], [2788, 5171, 5271]]
y = 400
print(add(x,y))

CodePudding user response:

Try this:

x = [[2873, 5321, 5421], [2788, 5171, 5271], [2788, 5171, 5271]]

y = 400

z = [[y   each for each in eachlist] for eachlist in x]
print (z)
# result: 
[[3273, 5721, 5821], [3188, 5571, 5671], [3188, 5571, 5671]]

CodePudding user response:

As another approach, if you wanted to go as far as using numpy you can use the following.

Depending on the size of your dataset, this approach might provide some efficiency gains over using nested loops, as numpy employs a method known as 'broadcasting' to apply a given operation to each value in the array, rather than ‘conventional looping’.

Additionally, this method scales well as it’s flexible to the shape of the lists.

For example:

import numpy as np

x = [[2873, 5321, 5421], [2788, 5171, 5271], [2788, 5171, 5271]]
a = np.array(x)

a   400

Output:

array([[3273, 5721, 5821],
       [3188, 5571, 5671],
       [3188, 5571, 5671]])
  • Related