To remove all integers, do this:
no_integers = [x for x in mylist if not isinstance(x, int)]
However, your example list does not actually contain integers. It contains only strings, some of which are composed only of digits. To filter those out, do the following:
no_integers = [x for x in mylist if not (x.isdigit()
or x[0] == '-' and x[1:].isdigit())]
Alternately:
is_integer = lambda s: s.isdigit() or (s[0] == '-' and s[1:].isdigit())
no_integers = filter(is_integer, mylist)
Answer from Daniel Stutzbach on Stack OverflowTo remove all integers, do this:
no_integers = [x for x in mylist if not isinstance(x, int)]
However, your example list does not actually contain integers. It contains only strings, some of which are composed only of digits. To filter those out, do the following:
no_integers = [x for x in mylist if not (x.isdigit()
or x[0] == '-' and x[1:].isdigit())]
Alternately:
is_integer = lambda s: s.isdigit() or (s[0] == '-' and s[1:].isdigit())
no_integers = filter(is_integer, mylist)
None of the items in your list are integers. They are strings which contain only digits. So you can use the isdigit string method to filter out these items.
items = ['1','introduction','to','molecular','8','the','learning','module','5']
new_items = [item for item in items if not item.isdigit()]
print new_items
Link to documentation: http://docs.python.org/library/stdtypes.html#str.isdigit
I have this code:
list = [1,2,3,4,5,6,7,8,9]
for x in list:
if x<5:
list.remove(x)
listBut it returns [2,4,6,7,8,9] instead of [5,6,7,8,9]
Why does it do this and how do I fix it?
python - Removing number from list of numbers - Stack Overflow
removing numbers form list by python - Stack Overflow
Remove numbers from list with list comprehension
Remove strings from a list that contains numbers in python - Stack Overflow
When you remove from same list, of course the index will be out of range items from list,
BUT you really don't need to remove those items from list, just don't include them in your sum calculation:
n = int(input("Enter number of elements : "))
a = list(map(int, input("\nEnter the numbers : ").strip().split()))
b = sum([num for num in a if num<= 9])
print(b)
You can use this if you want to remove numbers less than 10 from the list and Calculate the sum of the remaining numbers
n = int(input("Enter number of elements : "))
a = list(map(int, input("\nEnter the numbers : ").strip().split()))
if len(a) == n:
for num in a:
if num < 9:
a.remove(num)
print('sum',sum(a))
else:
print(f"You must enter {n} number")
How could I complete this string comprehension?
words = [word for word in words if int(word)โฆ # raises an error]
Thank you
Without regex:
[x for x in my_list if not any(c.isdigit() for c in x)]
I find using isalpha() the most elegant, but it will also remove items that contain other non-alphabetic characters:
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. Alphabetic characters are those characters defined in the Unicode character database as โLetterโ
my_list = [item for item in my_list if item.isalpha()]
If your only goal is to keep those two elements, you can do:
import string
number_list = ["December 31, 2020", "10.00%", "$50", "1,452", "7", "testing", "(1)", "(1000)"]
new_list = []
garbage_list = []
for elem in number_list:
new_list.append(elem) if set(elem.lower()) & set(string.ascii_lowercase) else garbage_list.append(elem)
print(new_list)
The key idea is that I use the & operator (intersection) between the set of lowercase characters and the element we have reached in our iteration. If the set is nonempty, then that means there is a character and we want to keep it in our new set.
Note that string.ascii_lowercase is just the string abcde...xyz.
Output:
['December 31, 2020', 'testing']
It would be much better if you could tell what all kind of values are kept in number_values like date/time (in other formats), currency (other formats like 500 won), etc which you may or may not want to keep.
I can see that you want to keep first a date format and a string, and exclude everything else, which can be done be like this:
number_list = ["December 31, 2020", "10.00%", "$50", "1,452", "7", "testing", "(1)", "(1000)"]
new_list = []
garbage_list = []
for i in number_list:
// only check for first or second character for digits
if i[0].isdigit() or i[1].isdigit():
garbage_list.append(i)
else:
new_list.append(i)
print(new_list)
Output:
['December 31, 2020', 'testing']
More information would require a robust solution.
Use lookarounds to check if digits are not enclosed with letters or digits or underscores:
import re
list_1 = ['what are you 3 guys doing there on 5th avenue', 'my password is 5x35omega44',
'2 days ago I saw it', 'every day is a blessing',
' 345000 people have eaten here at the beach']
for l in list_1:
print(re.sub(r'(?<!\w)\d+(?!\w)', '', l))
Output:
what are you guys doing there on 5th avenue
my password is 5x35omega44
days ago I saw it
every day is a blessing
people have eaten here at the beach
Regex demo
One approach would be to use try and except:
def is_intable(x):
try:
int(x)
return True
except ValueError:
return False
[' '.join([word for word in sentence.split() if not is_intable(word)]) for sentence in list_1]