+ 2
Taking a list of lists and adding the items of another list to each individual list in the list of lists? ... (Bear with me)
(Python3) Trying to take list a = [3,2,1] And adding it to the items in the list of lists b = [[1,2,3] , [4,5,6]] To get a new list of lists c = [[4,4,4] , [7,7,7]] Help?
2 ответов
+ 6
Here's a fairly simple way to do it;
a = [3,2,1]
b = [[1,2,3], [4,5,6]]
c = []
for sublist in b:
d = []
for index, val in enumerate(sublist):
d.append(val+a[index])
c.append(d)
print(c)
+ 4
Another way is to use numpy arrays instead of lists. Take a look at the numpy module:
https://www.sololearn.com/learn/6671/
Then, doing a + b will return a new array with the values summed elementwise. If you’ll be doing this opperation too often, you should probably go with numpy.