rh1990
rh1990

Reputation: 940

Deleting elements in a list by their value as index

I have a list which is days in a time series that doesn't start at zero:

days = [2,3,4,5,...]

I have another list which is minutes of cloud on all days starting at day 0:

weather = [0,120,150,60,120,30,300,...]

I want to iterate through days, and remove it if the corresponding index in weather is greater than some value.

I've tried

downtime = 100
days_new = [x for i, x in enumerate(days) if weather[i] < downtime]

Which should then result in:

days_new = [3,5,...]

as the indexes removed (2,4) have a value greater than 100 in the list weather.

But it's removing them based off the index of days not its value as an index. I.e. this only works if my list starts at 0, not any integer greater than 0. How can I fix this?

Upvotes: 1

Views: 76

Answers (4)

Md. Rezwanul Haque
Md. Rezwanul Haque

Reputation: 2950

You can try this way:

days = [2,3,4,5,...]
weather = [0,120,150,60,120,30,300,...]
downtime = 100
days_new = []
for x in days:
    if weather[x] < downtime:
        days_new.append(x)

# output :
days_new = [3, 5,...]

Upvotes: 0

Ajay2588
Ajay2588

Reputation: 567

You can try this

[x for x in days if weather[x] <= 100]

Output, for your input:

[3, 5]

Upvotes: 1

Talita
Talita

Reputation: 835

If weather is given for all days and day from days is an index in weather:

downtime = 100
new_days = [day for day in days if weather[day] <= downtime]

Upvotes: 1

Moses Koledoye
Moses Koledoye

Reputation: 78554

Your requirement assumes weather is subscriptable by all the items in days, in which case you wouldn't need enumerate. Index weather directly with the indices in days:

days_new = [x for x in days if weather[x] < downtime]

Upvotes: 4

Related Questions