Friday, 27 December 2019
python - How to detect non-number of the list?
Answer
Answer
Suppose I have a list as the following:
a = ['111', 213, 74, '99', 't', '88', '-74', -74]
The list contains number-like string, number and string of the data types.
I consider number-like string can convert number, so it's can see as a number.
This is my method:
a = ['111', 213, 74, '99', 't', '88', '-74', -74]
def detect(list_):
for element in list_:
try:
int(element)
except ValueError:
return False
return True
print detect(a)
But it looks so lengthy and unreadable, so anyone has better method to detect it?
Additionally, my list contains negative number and negative-number-like string, how do I do?
Answer
For only positive integers:
not all(str(s).isdigit() for s in a)
For negatives:
not all(str(s).strip('-').isdigit() for s in a)
For decimals and negatives:
not all(str(s).strip('-').replace('.','').isdigit() for s in a)
Subscribe to:
Post Comments (Atom)
php - file_get_contents shows unexpected output while reading a file
I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...
-
I have an app which needs a login and a registration with SQLite. I have the database and a user can login and register. But i would like th...
-
I would like to split a String by comma ',' and remove whitespace from the beginning and end of each split. For example, if I have ...
-
I got an error in my Java program. I think this happens because of the constructor is not intialized properly. My Base class Program public ...
No comments:
Post a Comment