Skip to content Skip to sidebar Skip to footer

Multiple Commands Within A For-loop, Multiple For-loops, Or Something Else?

For a task (i.e. no pandas or anything that would make it easier), I have to plot a polygon in python3/numpy/Matplotlib, but the data file is giving me trouble at the first hurdle

Solution 1:

Alright, what you have to do is insert another for loop under your original one, like this

for replace in Poly.readlines():
    #Replace the extraneous information ("(",",",")") with nothing, rather than multiple commands to strip and remove them. Stack Overflow Source for idea: https://stackoverflow.com/questions/390054/python-strip-multiple-characters.
    replace = replace.replace('(','').replace(',','').replace(')','')
    x,y=replace.split("#where you want to split?")
    data_easting.append(x)
    data_northing.append(y)

Solution 2:

You seem to be pushing your code in all the wrong directions. You need to learn how to debug small programs.

With data processing like this you should print out the results as you go and you will see what the data looks like at each stage.

Perhaps you meant this:

data_easting=[]
data_northing=[]
    
#Open the .dat file (in Python)
Poly = open('poly.dat','r')
    
#Loop over each line of poly.dat.for replace in Poly.readlines():
    replace = replace.strip()
    if replace:
        replace = replace.replace('(','').replace(',','').replace(')','')
        print(replace)
        x,y = replace.split()
        data_easting.append(x)
        data_northing.append(y)

Update: Used strip() to clean up blank lines.

Solution 3:

#Assign columns
data_easting=[]
data_northing=[]
    
#Open the .dat file (in Python)
Poly = open('poly.dat','r')
    
#Loop over each line of poly.dat.for line in Poly.readlines():
    line = line.replace('(', '')
    line = line.replace(')', '')
    xy_tuple = line.split(',')
    data_easting.append(xy_tuple[0].strip())
    data_northing.append(xy_tuple[1].strip())
Poly.close()    

Post a Comment for "Multiple Commands Within A For-loop, Multiple For-loops, Or Something Else?"