Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
659 views
in Technique[技术] by (71.8m points)

list - Floats not evaluating as negative (Python)

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,
    -0.006015995850622406, 
    -0.08920269709543568,   
    -25.72356846473029,
    -9.770807053941908, 
    -66.38340248962655, 
    -188.7778008298755,
    -165.95850622406638,
    99.99,
    33.81404564315352,
    0.1742564315352697,
    -0.00560109958506224,
    -0.008297925311203318,
    -1.4044238589211617
]

After I run a for loop that says if num<0: list.remove(num) the list looks like this:

[
    0.030079979253112028,
    -0.08920269709543568,
    -9.770807053941908,
    -188.7778008298755,
    99.99,
    33.81404564315352,
    0.1742564315352697,
    -0.008297925311203318
]

So some of the negative vlues, like -66.383... got deleted, but others didn't. Why is this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)] 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...