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

2024-09-29 23:28:01 发布

您现在位置: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)) 

有没有办法将每个块压缩成一个变量,而不是多次复制和粘贴这些数据?我尝试过定义函数,但是由于代码块没有参数,所以没有意义。你知道吗


Tags: andthefromforisrandomitemvariable
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公司

您可以将其提取到函数中,以避免重复代码。例如:

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)

相关问题 更多 >

    热门问题