B.Mr.W.
B.Mr.W.

Reputation: 19628

Python List Comprehensions try

I have a list that looks like this:

target = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '...', '1458', 'Next']

I am wondering, is there a one-line list comprehension solution to find the highest number in the list:

I have tried:

max([int(num) for num in text])

...but it seems like some of the text cannot be converted and there is no try except in the list comprehension.

I CAN ONLY ACCEPT A ONE LINE SOLUTION, PLEASE

my code:

text = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '...', '1458', 'Next']
print text
max = 0
for num in text:
    try:
        if int(num) > max:
            max = int(num)
    except:
        pass
print max

Upvotes: 0

Views: 372

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121924

You can use str.isdigit() to test if the string can be converted:

max(int(num) for num in text if num.isdigit())

A generator expression is enough here, no need to create an intermediary list.

Demo:

>>> text = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '...', '1458', 'Next']
>>> max(int(num) for num in text if num.isdigit())
1458

Note that int() also tolerates whitespace; if you suspect your input list has whitespace around the numbers, you can add a str.strip() call too to widen the net a little:

max(int(num) for num in text if num.strip().isdigit())

If you need to support signed values too (an initial - or +) you could try:

max(int(num) for num in text if num.strip().lstrip('-+').isdigit() and num.count('-') + num.count('+') <= 1)

for an even more exhaustive test. int() is a little more tolerant still but this is more than close enough for most cases; if you want to capture each and every possibility you'd have to resort to regular expressions.

Demo:

>>> text = [' +2 ', '-3', '     4', '5    ', '6', '7', '8', '9', '10', '...', '  +1458  ', 'Next']
>>> max(int(num) for num in text if num.strip().lstrip('-+').isdigit() and num.count('-') + num.count('+') <= 1)
1458

Upvotes: 13

Related Questions