Floats not evaluating as negative (Python)

后端 未结 2 1902
南笙
南笙 2020-12-04 01:01

I am trying to delete floating point values in a list that are negative. The original list with all of the values looks like this:

[
    0.030079979253112028         


        
相关标签:
2条回答
  • 2020-12-04 01:43

    To provide an illustration in what is happening here and why mutating a sequence you are currently iterating over is a bad idea:

    1, -1, -1, 0
    ^ # this is your iterator starting at the beginning
    
    1, -1, -1, 0
        ^  # after on step we are here your function has deemed this value unworthy 
    
    1, _, -1, 0
       ^  # the value has been removed but we can't have an empty space so everything gets moved forward
    
    1, -1, 0
        ^  # now everything has shifted forward but our iterator has not moved.
    
    1, -1, 0
           ^  # Our iterator goes to the next step without ever having evaluated the value that got shifted in to the removed values place.
    

    You will notice the pattern in you results that the negatives that remain in your list are always preceded by another negative originally. It's better practice to create a new list of leaving out the values or objects you don't need:

    new_list = [x for x in old_list if foo(x)] 
    
    0 讨论(0)
  • 2020-12-04 01:45

    You are iterating over and mutating the list which means you end up removing the wrong elements, you can use reversed:

    for num in reversed(lst):
        if num < 0:
            lst.remove(num)
    

    Or make a copy:

    for num in lst[:]:
        if num < 0:
            lst.remove(num)
    

    You can also use a list comp to modify the original list:

    lst[:] = [num for num in lst if num >= 0]
    
    0 讨论(0)
提交回复
热议问题