0

In Python, how do I build an array of coordinates given 2 lists of axes, such that the output array contains all the possible coordinate pairs?

e.g.

ax1=[1,3,4]
ax2=[a,b]

"""
Code that combines them
"""

Combined_ax1 = [1,3,4,1,3,4,1,3,4]
Combined_ax2 = [a,a,a,b,b,b,c,c,c]

I need this so I can feed combined_ax1 and combined_ax2 into a function without using multiple for loops.

4
  • Use itertools.product Commented Nov 15, 2016 at 17:39
  • take a look at this: stackoverflow.com/questions/533905/… Commented Nov 15, 2016 at 17:39
  • 4
    Combined_ax2, Combined_ax1 = zip(*itertools.product(['a', 'b', 'c'], [1, 3, 4])) gets you (1, 3, 4, 1, 3, 4, 1, 3, 4) and ('a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c') Commented Nov 15, 2016 at 17:39
  • Where did c come from? Commented Nov 15, 2016 at 17:47

2 Answers 2

2

This code would get what you require

import itertools

ax1=[1,3,4]
ax2=['a','b']

Combined_ax1, Combined_ax2 = zip(*itertools.product(ax1, ax2))
Sign up to request clarification or add additional context in comments.

Comments

-1

This can be done by using a list comprehension as follows:

cartesian_product = [(x, y) for x in ax1 for y in ax2]

This code sample will return a list of tuples containing all possible pairs of coordinates.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.