Home > Back-end >  Is it possible to rearrange my list so that my list indexes matches the hour of the day?
Is it possible to rearrange my list so that my list indexes matches the hour of the day?

Time:11-12

I have a list of 24 prices between each hour of the day and night.

example:

Pricelist = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]

I have also imported time that returns the current time: eg. N = 13. I want to rearrange the Pricelist so that PriceList[N] gets put at index 0 in the list, and the next price gets index N 1.

The goal is to get a following list if N = 13:

Pricelist = [13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

CodePudding user response:

You can use list slicing and concatenation to achieve it:

Pricelist = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]
N = 13

Pricelist_new = Pricelist[N-1:]   Pricelist[:N-1]
# [13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

CodePudding user response:

So you need that N needs to be equal to the hour of the day? Have you tried

from datetime import datetime
currentDateAndTime = datetime.now()

N=currentDateAndTime.hour

This will make that N equals to the local hour

  • Related