2016-07-11 7 views
-1

私は複数のコードを複数回(順番に)繰り返す必要があります。ここに2つのブロックの例があります(さらに多くのブロックがあります)。複数回のPythonコードを繰り返します - それを凝縮する方法はありますか?

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

の代わりにコピーし、これらを複数回貼り付け、続い

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

、単一の変数に各ブロックを凝縮する方法はありますか?私は関数を定義しようとしましたが、コードブロックに引数がないので意味がありませんでした。

+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

関連する問題