Reputation: 447
h = [1, 2, 3, 2, 3, 3]
n = [[0], [0, 1], [0, 1, 2], [0], [0, 1], [0]]
I want to add each int in h to each list in n, such that I get:
result = [[1], [2, 3], [3, 4, 5], [2], [3, 4], 3]]
I have failed with:
z = []
for i in h:
for i2 in n:
k = i + i2
z.append(k)
I understand why this fails but I don't know the way forward
Upvotes: 0
Views: 212
Reputation: 61
You can use new result array
result = []
for i in range(len(h)):
intermediate = []
for j in n[i]:
intermediate.append(j + h[i])
result.append(intermediate)
Upvotes: 1
Reputation: 323226
You can using
z=[[z + x for z in y ]for x , y in zip(h,n)]
z
[[1], [2, 3], [3, 4, 5], [2], [3, 4], [3]]
Upvotes: 2
Reputation: 594
new_n = [[int_n+h[i] for int_n in list_n] for i,list_n in enumerate(n)]
Among other solutions.
It's not very different from what you have tried, but uses a more compact syntax and takes advantage of enumerate() which you should use every time you loop on some list-like object
And what you tried doesn't work because when you do :
for i2 in n:
i2 will be each list in n, and not each integer because n is a list of lists.
Upvotes: 1