I have a list consisting of multiple nested dictionaries and nested lists
MyList = [{dict0}, {dict1}, {dict2} ... {dict2422}]
dict0 = {'type': 'Feature', 'geometry': {'type': 'Polygon', 'coordinates': [[[1, 2], [1, 2], [ [3, 4], [3, 4]]]}}
dict1 = {'type': 'Feature', 'geometry': {'type': 'Polygon', 'coordinates': [[[1, 2], [1, 2], [ [3, 4], [3, 4]]]}}
I have tried the following by help from comments:
coords = sum((x['coordinates'] for item in features if 'coordinates' in (x :=item.get('geometry',{}))),start=[])
which results in:
coords = [[[1, 2], [1, 2]],
[[3, 4], [3, 4]],
[[5, 6], [5, 6]]]
I want to plot these lists seperately from eachother so:
coords1 = [[1, 2], [1, 2]]
coords2 = [[3, 4], [3, 4]]
coords3 = [[5, 6], [5, 6]]
and then plotting the first row of coords1
as x coordinate, second row as y coordinate. And then do the same for coords2.
The entire coords
list consists of ~2244 lists like this, each list of seperate landmass coastline xy coordinates, so coords1
is landmass 1, which is why the coords1
and coords2
need to be plottet independently
I tried to combine all the first elements of each lists and second elemnts of each lists to each their own new list
flatlist = [el for lst1 in coords for lst2 in lst1 for el in lst2]
x, y = flatlist[0::2], flatlist[1::2]
But plotting this just gives connecting lines between landmasses coastlines as its just 2 long lists of coordinates.
So how do I seperate the original coords
list into multiple lists, coords1
, coords2
, coords3
and so fourth, and then plot it? I know simple plots, but the coords
has ~2244 lists in it and don't how to plot it without making 2244 lines of code. I assume a looped plot but I don't know how to. The coords
list does not need to be seperated if plotting directly from it is possible.
CodePudding user response:
I belive this is what you are looking for,
a=[]
b=[]
for dic in MyList:
for i in range(len(dic["geometry"]["coordinates"])):
a.append(dic["geometry"]["coordinates"][i][0])
b.append(dic["geometry"]["coordinates"][i][1])
CodePudding user response:
Perhaps something like
coords = sum((item['geometry']['coordinates'] for item in MyList), start=[])
A "safe" version would be
coords = sum((x['coordinates'] for item in MyList if 'coordinates' in (x := item.get('geometry', {}))), start=[])
The standard idiom for transposing a list afterwards is
x, y = zip(*coords)