Search code examples
pythonarraysnumpysetpython-itertools

How to convert from a set to an array in python


The question:

I need to convert a set to an array. If I try to just do np.array(X), I get an array that contains a set, which isn't very helpful. If I convert my set to a list and then my list to an array, everything works fine, but that seems needlessly complex (the line of code in question is a convoluted mess of needless complexity already). Is there a way to go straight from set to array?


Code context, if helpful:

rad = 0.944
n = 5
pairs = np.array(list(set(chain.from_iterable(((x,y),(x,-y),(-x,y),(-x,-y)) for x in np.linspace(0, rad, n) for y in np.linspace(0, rad, n) if math.hypot(x,y) <= rad))))

The point of the set is to remove duplicates from the chain. I know there are ways of doing this with an array, but it doesn't seem possible to convert an itertools.chain object directly into an array either.

Holistically, this code just models a circle using a uniform distribution of x,y points, and speeds up the process by evoking symmetry between the four quadrants.


Solution

  • My conclusion is that there is no easier way to convert a set to an array other than going through a list first.

    In terms of my particular situation, I ended up using the following:

    rad = 0.944
    n = 5
    pairs = np.array([item for item in itertools.product(np.linspace(-rad, rad, 2*n-1), repeat=2) if math.hypot(item[0], item[1]) <= rad])