1

For example, if I have the following arrays:

arraya = ['z', 'q']
arrayb = ['t', 'f']

I'd like to use the items from each list to create 'pairs' and get the following output:

['zt', 'zf', 'qt', 'qf']

I know I can figure out a jury-rigged way to write a function that produces this result, but a prebuilt function would be better for my purposes.

NaHCO3
  • 31
  • 6
  • Multiplication is mathematically not defined in vector operations, which makes me doubt there is a pre-built method for this. It looks like you are going to have to brute force this method due to it's rather specific needs. – Easton Bornemeier Jun 08 '17 at 22:01
  • What application are you trying to use this for that makes you think of this operation as "multiplication"? Are you trying to implement polynomial multiplication or something? – user2357112 Jun 08 '17 at 22:05
  • Sorry, wrong word choice. Bad on me. I more correctly meant something along the lines of array item permutations, using the items of two different lists. I`ll update the question to reflect this. – NaHCO3 Jun 08 '17 at 22:11

2 Answers2

1

This is as close to a built-in as you'll be able to get.

>>> import itertools
>>> [''.join(x) for x in itertools.product(arraya, arrayb)]
['zt', 'zf', 'qt', 'qf']

Find the cartesian product of the 2 lists/arrays and then concatenate the product.

cs95
  • 379,657
  • 97
  • 704
  • 746
0

There is no builtin function for this, but you could use senderle's cartesian_product or pv's cartesian function. Which is faster may depend on your use case. Then the following yields the desired result:

In [40]: cartesian_product([['z', 'q'], ['t', 'f']]).ravel().view('<U2')
Out[40]: 
array(['zt', 'zf', 'qt', 'qf'], 
      dtype='<U2')

These functions can be faster than using itertools.product. For example,

In [181]: x, y = np.arange(500), np.arange(500)

In [185]: %timeit cartesian_product([x, y])
1000 loops, best of 3: 797 µs per loop

In [184]: %timeit cartesian_product2([x, y])
1000 loops, best of 3: 1.44 ms per loop

In [186]: %timeit cartesian([x, y])
100 loops, best of 3: 4.71 ms per loop

In [100]: %timeit np.array(list(IT.product(x, y)))
10 loops, best of 3: 112 ms per loop
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677