7

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?

Burger King
  • 2,945
  • 3
  • 20
  • 45
  • 2
    It is a bit lengthy but definitly not unreadable. But you should replace `except:` with `except ValueError:` and lift the `try-except` to wrap the `for`loop instead of individual elements – WorldSEnder Oct 09 '15 at 02:44
  • Although commenting the exception make it more readable, I hope it can be simplified one-line code. – Burger King Oct 09 '15 at 02:46

3 Answers3

6

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)
Burger King
  • 2,945
  • 3
  • 20
  • 45
Hayley Guillou
  • 3,953
  • 4
  • 24
  • 34
3
a = ['111', 213, 74, '99', 't', '88']

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

['t']
LetzerWille
  • 5,355
  • 4
  • 23
  • 26
2
a = ['111', 213, 74, '99', 't', '88']

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

print detect(a)
Hooting
  • 1,681
  • 11
  • 20