简体   繁体   中英

Call function multiple times with a loop

I have made a function which produces a map, which I will turn into a gif by plotting 24 versions of the map representing the 24 hours in a day. I can call my map the following way.

get_gif(0.0, '00:00:00', '00.png')

to print the next map I will call the following:

get_gif(1.0, '01:00:00', '01.png')

And so on until up to my final call which will look like this:

get_gif(23.0, '23:00:00', '23.png')

How would I make a loop so that I can make all 24 calls in one go? My first argument is a float between 0.0 to 23.0 (the hours of the day), then a string for the time which I am printing in the map, then another string which is the file name.

For python3.6 and above:

for hour in range(24):
    get_gif(float(hour), f"{hour:02}:00:00", f"{hour:02}.png")

What you need is a string formatter. In python that would be something like

'{0}.png'.format(n)

In python the '{0}'.format(n) will replace the {0} with the number n. The variable n can be updated with a for loop. Unfortunately it seems that your file contain things like '01.png' so you cannot do

'{0}.png'.format(1)

Because the name will become 1.png. For this reason you can use an if clause and use

'0{0}.png'.format(n) 

If n is smaller then 10.

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