Reputation:
I'm having trouble figuring out a code to write that will merge a two dimensional list to a three dimensional list. For example, "a" is two dimensional list and "b" is three dimensional list that i would like to merge them two together and sort in order. If this is possible can this be done with witting a list comprehension? For another example here is my two list below.
a = [[7, 28],[28],[28]]
b = [[[3, 9],[3, 9],[3, 9]],[[3, 4],[4, 7],[4, 7]],[[7, 11],[3, 11],[3, 7, 12]]]
I would like my result to be
c = [[[3, 7, 9, 28],[3, 7, 9, 28],[3, 7, 9, 28]],
[[3, 4, 28],[4, 7, 28],[4, 7,28]],
[[7, 11, 28],[3, 11, 28],[3, 7, 12, 28]]]
Upvotes: 0
Views: 98
Reputation: 6935
Try this :
c = [[sorted(i+k) for k in j] for i,j in zip(a,b)]
Output :
[[[3, 7, 9, 28], [3, 7, 9, 28], [3, 7, 9, 28]],
[[3, 4, 28], [4, 7, 28], [4, 7, 28]],
[[7, 11, 28], [3, 11, 28], [3, 7, 12, 28]]]
Here is another way without one-liner :
c = b[:]
for i,j in zip(a,c):
for k in j:
k.extend(i)
k.sort()
Upvotes: 0
Reputation: 25564
another 1-liner, using enumerate
instead of zip
:
c = [[sorted(s1+a[i]) for s1 in s0] for i, s0 in enumerate(b)]
Upvotes: 0
Reputation: 2518
This should work:
c = [[sorted(i+x) for i in y] for x, y in zip(a,b)]
print(c)
#[[[3, 7, 9, 28],[3, 7, 9, 28],[3, 7, 9, 28]],[[3, 4, 28],[4, 7, 28],[4, 7,28]],[[7, 11, 28],[3, 11, 28],[3, 7, 12, 28]]
Upvotes: 0
Reputation: 22503
In case you fancy a oneliner:
result = [[sorted(i+x) for i in y] for x, y in zip(a,b)]
print (result)
#[[[3, 9, 7, 28], [3, 9, 7, 28], [3, 9, 7, 28]], [[3, 4, 28], [4, 7, 28], [4, 7, 28]], [[7, 11, 28], [3, 11, 28], [3, 7, 12, 28]]]
Upvotes: 1