Home > Blockchain >  Erasing Floats and other numbers less than n from a list
Erasing Floats and other numbers less than n from a list

Time:09-27

I have a list of ints/floats, below I have a for loop which goal it is to delete all numbers less than 1000 from the list.

percentages = [2000, 10, 69.29]

for percentage in percentages:
    if percentage < 1000:
        print("PASS")
        n = percentages.index(percentage)
        del percentages[n]

    if percentage >= 1000:
        print("Qualified")

print(percentages)

However, decimal numbers are completely ignored. What am I doing wrong?

CodePudding user response:

You can filter the list without using an explicit loop.

percentages = [2000, 10, 69.29]
percentages = filter(lambda x: x > 1000, percentages)
percentages = list(percentages)

print(percentages)

CodePudding user response:

Try list comprehension -

percentages = [2000, 10, 69.29]

percentages = [i for i in percentages if i > 1000]

print(percentages)

CodePudding user response:

You can add the numbers to list comprehension while filtering them with the necessary conditions.

percentages = [2000, 10, 69.29]
print([n for n in percentages if n > 1000 or type(n) is not float])

CodePudding user response:

try this:

percentages = [2000, 10, 69.29]

newPercentages = []
for percentage in percentages:
    if percentage < 810:
        pass

    if percentage >= 810:
        newPercentages.append(percentage)

print(newPercentages)

This appends everything into a new list, but I think that's fine

CodePudding user response:

The reason for this behavior is you are deleting an element from the list while iterating over it. Try printing the list in the for loop and you will get to know the behavior. Try out this code which gives the correct results.

percentages = [2000, 10, 69.29, 70]
out = []

for percentage in percentages:
    if percentage < 1000:
        print("PASS") 
    if percentage >= 1000:
        print("Qualified")
        out.append(percentage)

print(out)

Output:

Qualified
PASS
PASS
PASS
[2000]

CodePudding user response:

Use,

percentages = [2000, 10, 69.29]
percentages = [i for i in percentages if i > 1000]

List compression is just a short and more effecient way to write a for loop. Here i is appended to a list if i is bigger than 1000. So It basically filter the list for everything below 1000

  • Related