Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Test if value can be converted to an int in a list comprehension

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?

like image 243
Bolster Avatar asked Apr 09 '11 17:04

Bolster


People also ask

How do you check if a value can be converted into integer in Python?

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.

How do you check if an element is a number in Python?

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 .

How do you convert a list to an int in Python?

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.

How do I convert an element to a list in int?

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.


2 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).

like image 89
Felix Kling Avatar answered Oct 14 '22 07:10

Felix Kling


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])] 
like image 37
tokland Avatar answered Oct 14 '22 07:10

tokland