简体   繁体   中英

Repeating python code multiple times - is there a way of condensing it?

I've got multiple blocks of code which I need to repeat multiple times (in sequence). Here's an example of two blocks (there are many more).

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

followed by

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

Instead of copying and pasting these multiple times, is there a way of condensing each block into a single variable? I've tried defining functions but as the code blocks don't have arguments it didn't make sense.

You could just extract this out into a function, to avoid repeating code. For example:

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)

I suggest you just make it a function. For instance:

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

I don't see how it would not make sense to put it into a function.

Hope this helps,

KittyKatCoder

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM