2016-07-11 2 views
-1

У меня есть несколько блоков кода, которые мне нужно повторять несколько раз (последовательно). Вот пример двух блоков (их еще много).Повторяя код 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)) 

Вместо копирования и вставки эти несколько раз, есть способ конденсации каждого блока в одну переменную? Я пробовал определять функции, но поскольку у блоков кода нет аргументов, это не имело смысла.

+0

Используйте цикл? – DavidG

+2

есть такая вещь, как функция в python? – matpol

+3

@matpol erm ... да? – jonrsharpe

ответ

3

Вы можете просто извлечь это в функцию, чтобы избежать повторения кода. Например:

def do_something_with(projection, data, input_list) 
    items = [] 

    ran_yr = np.random.choice(input_list, 1) 
    items += [(ran_yr[0], 1)] 

    for item in output: 
     projection.append(data.query("Year == %d and Season == '%d'" % item)) 

do_something_with(projection, sprwetseq, extremewet) 
2

Предлагаю вам просто сделать его функцией. Например:

def 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)) 

Я не понимаю, как было бы бессмысленно вводить его в функцию.

Надеется, что это помогает,

KittyKatCoder

Смежные вопросы