Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extracting last two letters from a list of names by python

I have list of names with male and female tags to them. I have to extract last two letters of the names and the tag as well. I have shown a sample from the list.

([['suzetta', 'f'],
  ['teresita', 'f'],
  ['kaja', 'f'],
  ['nikita', 'm'],
  ['ina', 'f'],
  ['viviene', 'f'],
  ['lancelot', 'm'],
  ['nolan', 'm'],
  ['clayton', 'm'],
  ['almire', 'f'],
  ['ernest', 'm'],
  ['aubert', 'm'],
  ['kelsi', 'f'],
  ['phillipe', 'm'],
  ['lillian', 'f'],
  ['giovanni', 'm'],
  ['rochell', 'f'],
  ['mag', 'f'],

The code I am using is :

def last(letters):
    A = (i[-2:] for i in letters)
    return A

It is not returning the expected output because of the male and female tags in the name. Is there any work around for this? Thanks in advance!!

The expected output should be something like this:

[['ta', 'f'], ['ta', 'f'], ['ja', 'f'], ['ta', 'm'], ['na', 'f']]

like image 238
kovid kaul Avatar asked Dec 31 '25 11:12

kovid kaul


1 Answers

Use a list comprehension:

inp = [['suzetta', 'f'], ['teresita', 'f'], ['kaja', 'f'], ['nikita', 'm'], ['ina', 'f']]
output = [[x[0][-2:], x[1]] for x in inp]
print(output)

This prints:

[['ta', 'f'], ['ta', 'f'], ['ja', 'f'], ['ta', 'm'], ['na', 'f']]
like image 187
Tim Biegeleisen Avatar answered Jan 03 '26 06:01

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!