多次重复python代码 - 有没有一种方法可以缩小它?

时间:2016-07-11 09:10:28

标签: python pandas

我有多个代码块,我需要重复多次(按顺序)。这是两个块的示例(还有更多)。

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

有没有一种方法可以将每个块压缩成单个变量,而不是多次复制和粘贴这些?我已经尝试过定义函数,但由于代码块没有参数,所以它没有意义。

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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