2

I have a list of days in a year:

days = [0,1,2,3,...,363,364,365]

And a list of minutes of cloud on that day that is the same length:

weather = [0,60,150,80,...,120,90,150]

I want to delete the items in days if the corresponding index value of weather is greater than some condition, e.g if

condition = 120

Then my days list would look like:

days_new = [0,1,3,...,364]

So I'm thinking of something like:

for i in xrange(len(days)):
    if weather[i] > condition:
        del days[i]

Is there a 'neater' way of doing these kind of operations?

edit: my days list won't necessarily correspond to their indexes, this is a simplified case

Tom Wyllie
  • 2,020
  • 13
  • 16
rh1990
  • 880
  • 7
  • 17
  • 32
  • 2
    simply for history, i wouldn't delete from the old list, i would creqate a new list and add items that meet the condition to it and omit ones that do not. Other than that, this idea looks solid – Jason V Jul 11 '17 at 12:02
  • 2
    Possible duplicate of [How can I delete values from corresponding lists?](https://stackoverflow.com/questions/45019685/how-can-i-delete-values-from-corresponding-lists) – cs95 Jul 11 '17 at 12:09
  • You've said in your question that you want to delete items if the index value is greater than some condition, but in the example you have removed the index `363` where `weather[363] == condition`, presenting 'greater than *or equal to*' logic. Which one do you require? – Tom Wyllie Jul 11 '17 at 13:53

2 Answers2

2

If the days don't match their index, you can still use list-comprehension and use enumerate to get the indices as the following:

days = [x for i, x in enumerate(days) if weather[i] <= condition]
Mohd
  • 5,523
  • 7
  • 19
  • 30
  • Why not use `zip()` instead? – Szabolcs Jul 11 '17 at 12:20
  • @Szabolcs just incase the `lists` don't have the same length – Mohd Jul 11 '17 at 12:22
  • Well `zip` is safe for that scenario, while your `enumerate` approach will cause `IndexError: list index out of range` if the length of the `days` list is bigger than the length of `weather`. – Szabolcs Jul 11 '17 at 12:27
  • This answer gives a logic error in the case where `weather[i] == condition`. OP said he wants to delete from the list if the value is greater than, not include in the list if the value is less than. A `<=` should be used instead of `<`. – Tom Wyllie Jul 12 '17 at 13:26
0

I would not suggest to mutate the state of the old list, create a new one rather:

>>> threshold = 60
>>> days = [0, 1, 2, 3]
>>> weather = [0, 60, 150, 80]
>>> [d for d, w in zip(days, weather) if w > threshold]

It will output:

[2, 3]
Szabolcs
  • 3,990
  • 18
  • 38