Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find first item with alphabetical precedence in list with numbers

Say I have a list object occupied with both numbers and strings. If I want to retrieve the first string item with the highest alphabetical precedence, how would I do so?

Here is an example attempt which is clearly incorrect, but corrections as to what needs to be changed in order for it to achieve the desired result would be greatly appreciated:

lst = [12, 4, 2, 15, 3, 'ALLIGATOR', 'BEAR', 'ANTEATER', 'DOG', 'CAT']

lst.sort()
for i in lst:
   if i[0] == "A":
      answer = i
print(answer)
like image 292
vs94 Avatar asked Feb 29 '16 04:02

vs94


People also ask

How do you sort a list with letters and numbers in Python?

Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest. Use the sort(reverse=True) to reverse the default sort order.

How do you sort a list by first element?

If you're sorting by first element of nested list, you can simply use list. sort() method.


3 Answers

First use a generator expression to filter out non-strings, and then use min() to select the string with the highest alphabetical presence:

>>> min(x for x in lst if isinstance(x, str))
'ALLIGATOR
like image 66
Raymond Hettinger Avatar answered Nov 17 '22 13:11

Raymond Hettinger


IIUC you could use isinstance to get sublist of your original list with only strings, then with sorted get first element by alphabetical sorting:

sub_lst = [i for i in lst if isinstance(i, str)]
result = sorted(sub_lst)[0]


print(sub_lst)
['ALLIGATOR', 'BEAR', 'ANTEATER', 'DOG', 'CAT']

print(result)
'ALLIGATOR'

Or you could use min as @TigerhawkT3 suggested in the comment:

print(min(sub_lst))
'ALLIGATOR'
like image 31
Anton Protopopov Avatar answered Nov 17 '22 13:11

Anton Protopopov


Another way is to filter the main list lst from intergers using filter built-in method:

>>> min(filter(lambda s:isinstance(s, str), lst))
'ALLIGATOR'
like image 5
Iron Fist Avatar answered Nov 17 '22 12:11

Iron Fist