Reputation: 13
I am working in Python for a coding project. I am stuck on something that seems like it should be a simple fix but haven't had much luck.
Let's say I have two lists, each consisting of smaller lists...
Buckets= [[1,2,3],[1,2,3],[1,2,3]]
Emptybuckets=[[1],[],[3]]
How could I add these together such that I get:
[[1,1,2,3],[1,2,3],[1,2,3,3]]
Ive tried emptybuckets.append(buckets)
, for
loops (for x in emptybuckets
...append
) etc.
Any suggestions would be greatly appreciated.
Upvotes: 1
Views: 72
Reputation: 4263
you can append the lists using numpy.
Buckets= [[1,2,3],[1,2,3],[1,2,3]]
Emptybuckets=[[1],[],[3]]
for item in zip(Buckets,Emptybuckets):
print(np.append(item[0],item[1],axis=0).astype(int))
output:
[1 2 3 1]
[1 2 3]
[1 2 3 3]
Upvotes: 0
Reputation: 20391
Use zip
to group corresponding indices together, then adding them is easy:
[a+b for a, b in zip(Buckets, Emptybuckets)]
# [[1, 2, 3, 1], [1, 2, 3], [1, 2, 3, 3]]
Or if you want it exactly how it is in your question, just sort each one as you go:
[sorted(a+b) for a, b in zip(Buckets, Emptybuckets)]
# [[1, 1, 2, 3], [1, 2, 3], [1, 2, 3, 3]]
Upvotes: 6
Reputation: 376
Alex Thornton's answer is correct, and I would say that you should include sorted
if you want the numbers ordered as you state in your question
[sorted(a+b) for a, b in zip(Buckets, Emptybuckets)]
Upvotes: 2