python-3.xcomputer-sciencecustom-lists

if and elif repetition


I would like to know if there is a way to make this type of code more succinct and automated so that I don't have to repeat the elif statements again and again.

ga is a list of cumulative seconds from 1 to whatever seconds I have recorded and I would like to separate every hour with the respective data frame from that hour is there a way to make this much simpler?

for i in range(len(ga)):
 if ga[i]<=3600:
    j.append(i)
 elif ga[i]<=7200:
    u.append(i)
 elif ga[i]<=10800:
    k.append(i)
 elif ga[i]<=14400:
    b.append(i)
 elif ga[i]<=18000:
    bi.append(i)
 elif ga[i]<=21600:
    bit.append(i)
 elif ga[i]<=25200:
    bitb.append(i)
 elif ga[i]<=28800:
    bitc.append(i)
 elif ga[i]<=32400:
    bitd.append(i)
 elif ga[i]<=36000:
    bite.append(i)

Solution

  • With list comprehensions:

    r = [[idx for idx, val in enumerate(
        ga) if 3600*level < val <= 3600*(1+level)] for level in range(9)]
    
    (j, u, k, b, bi, bit, bitc, bitd, bite) = r