Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

Append two arrays together into one? (Numpy/Python)

I currently have an array of strings and I'm trying to join it together with another array of strings to form a complete word to do some web parsing. For example:`

Var1    [A   B    C, .... ....]
Var2    [1   2     3]

where A and B are at a variable length and I'm trying to join them together like:``

`
C  [A+1   A+2   A+3
 B+1    B+2   B+3
C+1     C+2    C+3

Here's what I've tried

for param in np.nditer(Var2):
List = np.append(np.core.defchararray.add(Var1, Var2))

So I'm trying to add them together and then create a list of lists, but this isn't working. any ideas how to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Is this what you are trying to do:

In [199]: list1 = ['abc','foo','bar']
In [200]: list2 = list('1234')
In [201]: [[a+b for b in list2] for a in list1]
Out[201]: 
[['abc1', 'abc2', 'abc3', 'abc4'],
 ['foo1', 'foo2', 'foo3', 'foo4'],
 ['bar1', 'bar2', 'bar3', 'bar4']]

The equivalent using np.char.add and broadcasting:

In [210]: np.char.add(np.array(list1)[:,None], np.array(list2))
Out[210]: 
array([['abc1', 'abc2', 'abc3', 'abc4'],
       ['foo1', 'foo2', 'foo3', 'foo4'],
       ['bar1', 'bar2', 'bar3', 'bar4']], dtype='<U4')

For this small example the list comprehension version is faster.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...