问题
My first post on Python language as I am learning it.
I have a shape file that has around 10000 polygons.
I am trying to generate code like below that creates Polygon1, Polygon2 all the way to Polygon10000 using syntax like this:
polygon1 = shape(shapes[0])
polygon2 = shape(shapes[1])
polygon3 = shape(shapes[2])
polygon4 = shape(shapes[3])
.
.
polygon10000 = shape(shapes[9999])
So all I am trying to do is to write code that is much more smaller than having to write 10000 lines of code like above.
I came up with some syntax but none of this is really working:
Method 1- Just prints the required syntax in the log but does not execute it so I have to copy the output after the code runs (from console) and then paste it in the code and then run that code
for x in range(1,10):
print('polygon' '%d =' ' shape(shapes[' '%d' '])' % (x, x-1 ))
Method 2 - Does the job but still need to write 10000 lines of code to create all 10000 polygons
def automate(n):
return shape(shapes[n])
polygon1 = automate(0)
polygon2 = automate(1)
.
.
polygon10000 = automate(9999)
Any suggestions on doing this in a quicker and shorter way would be highly appreciated..
Thank you, Tina
回答1:
How about something like:
polygons = []
for i in range(10000):
polygons.append(shape(shapes[i])
Then you can reference the polygons
as polygons[j]
where j
is an index from 0 to 9999.
来源:https://stackoverflow.com/questions/58923835/code-that-creates-variables-and-increments-its-suffix