I'm trying to remove a zero value from the Python list

Asked 2 years ago, Updated 2 years ago, 39 views

for i in range(10,100):
    list_2.append(i)

for i in range(100,1000):
    list_3.append(i)

for i in list_2:
    str1 = str(i)
    for j in range(2):
        if int(str1[j]) == 0:
            list_2.remove(i)

for i in list_3:
    str2 = str(i)
    for j in range(3):
        if int(str2[j]) == 0:
            list_3.remove(i)

I'm going to make a two-digit list and a three-digit list, and I'm going to delete 10, 20, 100, 200, and so on The two-digit list is deleted normally, but why is it not in list error in list_3.remove(i) in the three-digit list?

python list

2022-09-20 20:05

3 Answers

for i in list_3:
    str2 = str(i)
    for j in range(3):
        if int(str2[j]) == 0:
            list_3.remove(i)
            break

If you look at the 2nd list_3 logic, Assuming that 100 (hereinafter, list_3[0]) has been entered

1 > Non-zero if door not clear

Delete list_3[0] because 0 > 0.

Delete list_3[0] because 0 > 0 (already..) Error occurred because list_3[0] is not present)

Therefore

1 > Non-zero if door not clear

Delete list_3[0] because 0 > 0. break

You have to do it.


2022-09-20 20:05

To make some improvements,

for i in list_2:
    str1 = str(i)
    #for j in range(2):
    #    #    if int(str1[j]) == 0:
    #        #        list_2.remove(i)
    if "0" in str1:
            list_2.remove(i)

To improve further,

list_2 = [ e for e in list_2 if "0" not in str(e) ]


2022-09-20 20:05

I think the party is over, but there's also a way to solve it mathematically.

import math

# Basic idea: 2070% 100 == 70 == 2070% 1000
# This case is true because the third digit is zero.
def has_zero(num) :

    # 10, 100, 1000... Divide it by and see if the rest of the previous one and the rest of the current one are the same.
    lastMOD = 0
    unit = 10;
    while num >= unit :
        thisMOD = num % unit
        if thisMOD == lastMOD :
            return True
        lastMOD = thisMOD
        unit = unit * 10;
    return False

# It works amazingly.
print(has_zero(10))
print(has_zero(207))
print(has_zero(6000))
print(has_zero(70060))
print(has_zero(77767))


2022-09-20 20:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.