Hi,

I am newie to python.

How I combine 2 multi-dimension array into one by column?
here is an exmaple:

a = 1 2 3
2 3 4
3 4 5

b = 4 5 6
6 7 8
8 9 1

the combined array should be
c = 1 2 3 4 5 6
2 3 4 6 7 8
3 4 5 8 9 1

So essentially, stack all 3 columns of b into the end of a. c is 3 by 6 array.
How can i do that in python? Thanks in advance.

First off, Python doesn't really have arrays unless you include some of the add on packages. Python uses lists, so I would suggest that you take a look at lists. Combining is a simple matter. You can iterate through the lists with a for loop, creating a new list with the combined pairs. Itertools will also do this but that may be more than you want. Post some code and we'll let you know our opinion on how you can improve it/get it to work.

One way to do this is using a high speed list comprehension ...

# combine two 2D lists using a list comprehension
# a list is Python's more flexible array container
 
a = [[1, 2, 3],
[2, 3, 4],
[3, 4, 5]]
 
b = [[4, 5, 6],
[6, 7, 8],
[8, 9, 1]]
 
c = []
c = [a[ix] + b[ix] for ix in range(len(a))]
print c
"""
my output -->
[[1, 2, 3, 4, 5, 6], [2, 3, 4, 6, 7, 8], [3, 4, 5, 8, 9, 1]]
"""

Like woooee says, study up on lists.

One way to do this is using a high speed list comprehension ...

# combine two 2D lists using a list comprehension
# a list is Python's more flexible array container
 
a = [[1, 2, 3],
[2, 3, 4],
[3, 4, 5]]
 
b = [[4, 5, 6],
[6, 7, 8],
[8, 9, 1]]
 
c = []
c = [a[ix] + b[ix] for ix in range(len(a))]
print c
"""
my output -->
[[1, 2, 3, 4, 5, 6], [2, 3, 4, 6, 7, 8], [3, 4, 5, 8, 9, 1]]
"""

Like woooee says, study up on lists.

Thanks so much. That's really neat code. Appreciated.

John

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.