Baz
Baz

Reputation: 13125

Convert list of MultiPolygons and Polygons to a single MultiPolygon

How do I create in a generic manner a MultiPolygon from a list of MultiPolygon and Polygon objects?

a = MultiPolygon([Polygon([(0, 0), (1, 1), (1, 0)])])
b = Polygon([(0, 0), (2, 1), (1, 0)])

I wish to perform an operation that results in the following object:

MultiPolygon([Polygon([(0, 0), (1, 1), (1, 0)]) , Polygon([(0, 0), (2, 1), (1, 0)])])

I'm not looking to create a union, I just wish to iterate all the polygons.

Upvotes: 1

Views: 1859

Answers (1)

Georgy
Georgy

Reputation: 13697

There is no functionality in Shapely that can make a list of polygons out of a list of both polygons and MultiPolygon objects. But you could write a simple generator function for that purpose:

from shapely.geometry import MultiPolygon, Polygon

a = MultiPolygon([Polygon([(0, 0), (1, 1), (1, 0)])])
b = Polygon([(0, 0), (2, 1), (1, 0)])
your_list = [a, b]


def to_polygons(geometries):
    for geometry in geometries:
        if isinstance(geometry, Polygon):
            yield geometry
        else:
            yield from geometry


result = MultiPolygon(to_polygons(your_list))
print(result.wkt)
# MULTIPOLYGON (((0 0, 1 1, 1 0, 0 0)), ((0 0, 2 1, 1 0, 0 0)))

Upvotes: 1

Related Questions