Skip to content
Advertisement

Is there a more efficient way to format this list

I have a list of coordinates, but I want to format them so they form a grid. Right now, for every element of the list, I’m checking what its value is and then formatting it. Is there a smarter, more efficient way to do this?

def convertDataToCoords(xCoords, yCoords):
    xSorted = []
    ySorted = []
 
    for y in yCoords:
        if y >= 0 and y <= 175:
            ySorted.append(150)
        elif y > 175 and y <= 275:
            ySorted.append(230)
        elif y > 275 and y <= 350:
            ySorted.append(310)
        elif y > 350 and y <= 450:
            ySorted.append(400)
        elif y > 450 and y <= 525:
            ySorted.append(480)
        elif y > 525  and y <= 600:
            ySorted.append(575)
        elif y > 600 and y <= 700:
            ySorted.append(650)
        elif y > 700 and y <= 775:
            ySorted.append(732.5)
        elif y > 775 and y <= 860:
            ySorted.append(830)
        elif y > 860 and y <= 950:
            ySorted.append(900)
        elif y > 950 and y <= 1050:
            ySorted.append(1000)
        else:
            ySorted.append(1090)

 
    for x in xCoords:
        if x >= 0 and x <= 150:
            xSorted.append(130)
        elif x > 150 and x <= 250:
            xSorted.append(230)
        elif x > 250 and x <= 350:
            xSorted.append(330)
        elif x > 350 and x <= 450:
            xSorted.append(430)
        elif x > 450 and x <= 550:
            xSorted.append(530)
        elif x > 550 and x <= 650:
            xSorted.append(630)
        elif x > 650 and x <= 750:
            xSorted.append(730)
        else: 
            xSorted.append(830)

Advertisement

Answer

You can replace if-else with the list of min, max and expected values:

X = [(0, 150, 130),
     (150, 250, 230),
     (250, 350, 330)]

Y = [(0, 175, 150),
     (175, 275, 230),
     (275, 350, 310)]


def convert(coords, items):
    result = []
    for coord in coords:
        for min_, max_, exp in items:
            if min_ < coord < max_:
                result.append(exp)
    return result


x_sorted = convert([100, 200, 300], X)
y_sorted = convert([50, 150, 250], Y)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement