Khalid Abdulla Khalid Abdulla - 2 months ago 7
Python Question

Python, create new list based on condition applied to an existing list of same length

Ok, I'm sure there is a very easy way to do this, but I'm rusty in python and I can't work out the pythonic way to do this.

I have a list, representing the hours of the day:

import numpy as np
hourOfDay = np.mod(range(0, 100), 24)


Then I want to create a new list which is a larger value
0.4
, when the hour is between
7
and
22
, and
0.2
otherwise.

There are several related posts here and here, but they're not quite what I want (they end up with a shorter list, I want the same-length list).

Assuming I needed to use list comprehension I tried this:

newList = [0.4 for hour in hourOfDay if hour <= 7 or hour >= 22 else 0.2]

Answer

Your list comprehension was slightly off. Also if you want 0.4 when the hour is between 7 and 22, you need 7<= hour <= 22:

import numpy as np
hourOfDay = np.mod(range(0, 100), 24)

newList = [0.4 if 7 <= i <= 22 else 0.2 for i in hourOfDay]

>>> newList
[0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.2, 0.2, 0.2, 0.2, 0.2]
Comments