Article From:https://segmentfault.com/q/1010000012153317
Question:

To remove the 0 elements in the list, add a condition to the loop, but it doesn’t work. Why?

b = [1,2,3,4,5,0]
c = []
for i in b:
    if c!=0:
        c.append(i)
print(c)
>>>[1, 2, 3, 4, 5, 0]

Answer 0:

holdif c != 0:Change toif i != 0:, What to judge isArray BMiddleElement IInstead ofcThis array

b = [1,2,3,4,5,0]
c = []
for i in b:
    if i != 0:
        c.append(i)
print(c)

Answer 1:

if i!=0

Answer 2:

[i for i in b if i != 0]

Leave a Reply

Your email address will not be published. Required fields are marked *