-3

I just wanted to know how I can shorten my code using loop in python, can someone help me? Thanks! I'm using Python-flask.


app.route('/data', methods=["GET", "POST"])

def data():


con = sqlite3.connect('tmonitor.db')
    con.row_factory = sqlite3.Row

    cur = con.cursor()
    cur.execute("SELECT * FROM monitors ORDER BY id DESC limit 1")

    rows = cur.fetchall()
    
    value = [row[1] for row in rows]

//to split the array
    value1 = '-'.join(str(e) for e in value)
    value2 = value1.split('-')


//Insert inside the loop to shorten the code


    Cell1_raw = value2[0]
    Cell2_raw = value2[1]
    Cell3_raw = value2[2]
    Cell4_raw = value2[3]
    Cell5_raw = value2[4]
    Cell6_raw = value2[5]
    Cell7_raw = value2[6]
    Cell8_raw = value2[7]
    Cell9_raw = value2[8]
    Cell10_raw = value2[9]

// To convert in integer (Also need to shorten the code)
    Temperature1 = int(Cell1_raw)
    Temperature2 = int(Cell2_raw)
    Temperature3 = int(Cell3_raw)
    Temperature4 = int(Cell4_raw)
    Temperature5 = int(Cell5_raw)
    Temperature6 = int(Cell6_raw)
    Temperature7 = int(Cell7_raw)
    Temperature8 = int(Cell8_raw)
    Temperature9 = int(Cell9_raw)
    Temperature10 = int(Cell10_raw)

// to shorten also
    data = [time() * 1000, Temperature1, Temperature2, Temperature3, Temperature4, Temperature5, Temperature6, Temperature7, Temperature8, Temperature9, Temperature10]


    response = make_response(json.dumps(data))

    response.content_type = 'application/json'

    return response

I added some comments for you to see what needs to be shorten, I'm still studying python, thank you so much!

davidism
  • 121,510
  • 29
  • 395
  • 339
Timato1
  • 49
  • 7

1 Answers1

1

Use list slices (and don't create a bunch of similarly named variables in the first place).

raw_cells = value2[:10]
temperatures = [int(x) for x in raw_cells]
data = [time() * 1000, *temperatures]

This can be further shortened by getting rid of the temporary lists.

data = [time() * 1000, *(int(x) for x in value2[:10])]

If value2 doesn't have more than 10 elements, you don't even need the slice.

chepner
  • 497,756
  • 71
  • 530
  • 681