2016-07-11 35 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

使用for循環? – 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