Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect non-number of the list? [duplicate]

Tags:

python

list

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?

like image 434
Burger King Avatar asked Oct 09 '15 02:10

Burger King


3 Answers

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)
like image 51
Hayley Guillou Avatar answered Oct 14 '22 00:10

Hayley Guillou


a = ['111', 213, 74, '99', 't', '88']

def detect(list_):
    try:
        map(int,list_)
        return True
    except ValueError:
        return False

print detect(a)
like image 45
Hooting Avatar answered Oct 13 '22 23:10

Hooting


a = ['111', 213, 74, '99', 't', '88']

print([x for x in a if not str(x).isdigit()])

['t']
like image 2
LetzerWille Avatar answered Oct 14 '22 01:10

LetzerWille