Python: Test if value can be converted to an int in a list comprehension
Question:
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?
Answers:
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])]
Or
return filter(lambda y: y[x].isdigit(), listOfLists)
or if you need to accept negative integers
return filter(lambda y: y[x].lstrip('-').isdigit(), listOfLists)
As fun as list comprehension is, I find it less clear in this case.
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?
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])]
Or
return filter(lambda y: y[x].isdigit(), listOfLists)
or if you need to accept negative integers
return filter(lambda y: y[x].lstrip('-').isdigit(), listOfLists)
As fun as list comprehension is, I find it less clear in this case.