Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to delete an element of a list which is greater than a value?

I have a function that takes a string as its input. The string can contain Integer numbers as well. I want to remove the spaces between the words and any integer that is greater than, for example, 5. How can I do this?

def my(str):
    x = [i for i in str]
    for items in x:
        if items == ' ':
            x.remove(items)
    new_items = [x for x in x if not x.isdigit()]
    return(new_items)

print(my('7 monkeys and 1 tiger'))

So far I have tried this. It removes both 7 and 1 from the string.
Here is the output:

['m', 'o', 'n', 'k', 'e', 'y', 's', 'a', 'n', 'd', 't', 'i', 'g', 'e', 'r']

But I wanted to remove only 7 but not 1.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can add all the requirements into a single list comprehension:

p = [x for x in '7 monkeys and 1 tiger' if ((not x.isdigit() and not x ==' ') or (x.isdigit() and int(x) < 5))]
print(p)

There are two choices, the index is a digit and less than 5: (x.isdigit() and int(x) < 5) or the index is not a digit and not a space either: (not x.isdigit() and not x ==' ').

Output: ['m', 'o', 'n', 'k', 'e', 'y', 's', 'a', 'n', 'd', '1', 't', 'i', 'g', 'e', 'r']

Or you can use print("".join(p)) to get a single string: monkeysand1tiger.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading