Ace
Ace

Reputation: 13

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)

Upvotes: 1

Views: 80

Answers (2)

attdona
attdona

Reputation: 18953

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

Upvotes: 0

Muhammad Karimi
Muhammad Karimi

Reputation: 81

Maybe, It doesn't general solution, but base of problem, you can made creative solution. Like the following code

# Put variable name in var
# These are empty lists that have already been defined
var = ["j", "u", "k", "b", "bi", "bit", "bitb", "bitc", "bitd", "bite"]
for i in range(len(ga)):
    # Finding var index base of ga[i] value.
    var_index = ga[i] // 3600
    if ga[i] % 3600 == 0 and ga[i] > 0:
        var_index -= 1
    # Add the ga index to the corresponding list
    eval(var[var_index] + ".append(" + str(i) + ")")

But it's better to use a dictionary instead of defining many variables. Like the following code.

# Define dictionary 
ch = {"j":[], "u":[], "k":[], "b":[], "bi":[],
      "bit":[], "bitb":[], "bitc":[], "bitd":[], "bite":[]}
# Dictionary keys
key = ["j", "u", "k", "b", "bi", "bit", "bitb", "bitc", "bitd", "bite"]
for i in range(len(ga)):
    # Finding key index base of ga[i] value.
    key_index = ga[i] // 3600
    if ga[i] % 3600 == 0 and ga[i] > 0:
        key_index -= 1
    # Add the ga index to the corresponding list in the dictionary
    ch[key[key_index]].append(i)

Upvotes: 1

Related Questions