-1

I've imported a list from a .txt file that looks like this

[['George Washington'],
 ['John Adams'],
 ['Thomas Jefferson'],
 ['James Madison'],
 ['James Monroe'],
 ['John Quincy Adams'],
 ['Andrew Jackson'],
 ['Martin Van Buren'],
 ['William Henry Harrison'],
 ['John TyIer'],
...

I want to sort the list by the length of the first name in ascending order and display only the top 6, but nothing I tried seemed to work. Any suggestions?

blinds0r
  • 13
  • 2
  • 2
    What have you tried so far? Do you know how to sort by a key? Can you extract the first word from each element? Do you know how to find the length of a string? Can you combine these three items into one function? – Brian61354270 Mar 09 '20 at 01:59

3 Answers3

2

This is a list of lists, which is a little weird. So you need to test not for just the fist name, which you can get by split()ing the name, but the first name of the first item in the list.

With that, you might do something like:

pres = [['George Washington'],
 ['John Adams'],
 ['Thomas Jefferson'],
 ['James Madison'],
 ['James Monroe'],
 ['John Quincy Adams'],
 ['Andrew Jackson'],
 ['Martin Van Buren'],
 ['William Henry Harrison'],
 ['John TyIer']
]

sorted(pres, key=lambda x: len(x[0].split()[0]), reverse=True)[0:6]

Which results in:

[['William Henry Harrison'],
 ['George Washington'],
 ['Thomas Jefferson'],
 ['Andrew Jackson'],
 ['Martin Van Buren'],
 ['James Madison']]

If you want to sort for shortest to longest, of course, you can just remove the reverse=True

Mark
  • 90,562
  • 7
  • 108
  • 148
2
l = [['George Washington'],
 ['John Adams'],
 ['Thomas Jefferson'],
 ['James Madison'],
 ['James Monroe'],
 ['John Quincy Adams'],
 ['Andrew Jackson'],
 ['Martin Van Buren'],
 ['William Henry Harrison'],
 ['John TyIer']]

l.sort(key = lambda x: len(x[0].split()[0]))
print(l[:6])
sahasrara62
  • 10,069
  • 3
  • 29
  • 44
1
List = [['George Washington'],
 ['John Adams'],
 ['Thomas Jefferson'],
 ['James Madison'],
 ['James Monroe'],
 ['John Quincy Adams'],
 ['Andrew Jackson'],
 ['Martin Van Buren'],
 ['William Henry Harrison'],
 ['John TyIer']]

def func(name):
    fname = name[0].split()[0]
    return  len(fname)

print(sorted(List,key=func)[:6])
823
  • 63
  • 8