我想知道是否有一种方法可以使这种类型的代码更简洁和自动化,这样我就不必一次又一次地重复elif语句。
ga是从1到我所记录的秒数之间的累积秒数列表,我想每小时将每个小时与相应的数据帧分开,是否有办法使这一过程变得简单得多?
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)
答案 0 :(得分:1)
也许,这不是一般性的解决方案,但是根据问题的所在,您可以提出创造性的解决方案。 像下面的代码
# 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) + ")")
但是最好使用字典而不是定义许多变量。像下面的代码。
# 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)
答案 1 :(得分:0)
具有列表理解力:
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