У меня есть несколько блоков кода, которые мне нужно повторять несколько раз (последовательно). Вот пример двух блоков (их еще много).Повторяя код python несколько раз - есть ли способ его конденсации?
#cold winter
wincoldseq = [] #blank list
ran_yr = np.random.choice(coldwinter,1) #choose a random year from the extreme winter variable
wincoldseq += [(ran_yr[0], 1)] #take the random year and the value '1' for winter to sample from
for item in wincoldseq: #item is a tuple with year and season, ***seq is all year and season pairs for the variable
projection.append(extremecold.query("Year == %d and Season == '%d'" % item))
с последующим
#wet spring
sprwetseq = [] #blank list
ran_yr = np.random.choice(wetspring,1) #choose a random year from the extreme winter variable
sprwetseq += [(ran_yr[0], 2)] #take the random year and the value '2' for spring to sample from
for item in sprwetseq: #item is a tuple with year and season, ***seq is all year and season pairs for the variable
projection.append(extremewet.query("Year == %d and Season == '%d'" % item))
Вместо копирования и вставки эти несколько раз, есть способ конденсации каждого блока в одну переменную? Я пробовал определять функции, но поскольку у блоков кода нет аргументов, это не имело смысла.
Используйте цикл? – DavidG
есть такая вещь, как функция в python? – matpol
@matpol erm ... да? – jonrsharpe