Basically I want to do this;
return [ row for row in listOfLists if row[x] is int ]
But row[x] is a text value that may or may not be convertible to an int
I'm aware that this could be done by:
try: int(row[x]) except: meh
But it'd be nice to do it is a one-liner.
Any ideas?
Python's isnumeric() function can be used to test whether a string is an integer or not. The isnumeric() is a builtin function. It returns True if all the characters are numeric, otherwise False.
Python String isnumeric() Method The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False. Exponents, like ² and ¾ are also considered to be numeric values. "-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the .
Use int() function to Convert list to int in Python. This method with a list comprehension returns one integer value that combines all elements of the list.
Method 1: Using eval() Python eval() function parse the expression argument and evaluate it as a python expression and runs Python expression(code), If the expression is an int representation, Python converts the argument to an integer.
If you only deal with integers, you can use str.isdigit()
:
Return true if all characters in the string are digits and there is at least one character, false otherwise.
[row for row in listOfLists if row[x].isdigit()]
Or if negative integers are possible (but should be allowed):
row[x].lstrip('-').isdigit()
And of course this all works only if there are no leading or trailing whitespace characters (which could be stripped as well).
What about using a regular expression? (use re.compile
if needed):
import re ... return [row for row in listOfLists if re.match("-?\d+$", row[x])]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With