1

I have a list of sublists of anagrams such as

L = [['terrible', 'elbirret'],
     ['supermonster', 'retsnomrepus'],
     ['you', 'uoy', 'oyu'],
     ['pears', 'reaps', 'spear', 'spera']]

How do I write a function that will give me the sublist or anagram group that has the longest anagrams.

i.e. if the list were

L = [['spear', 'pears', 'reaps'], ['monster', 'sternom']]

it would give me

['monster', 'sternom']
falsetru
  • 357,413
  • 63
  • 732
  • 636
joe smite
  • 98
  • 7

1 Answers1

4

Using max with a key function to get the list with longest strings:

>>> L = [['spear', 'pears', 'reaps'], ['monster', 'sternom']]
>>> max(L, key=lambda xs: len(xs[0]))
['monster', 'sternom']

UPDATE

What if there were multiple sublists with longest of the same length?

Find the maximum length. Filter sublist based on the length:

>>> L = [['largest', 'artlegs'], ['spear', 'pears', 'reaps'], ['monster', 'sternom']]
>>> M = max(len(xs[0]) for xs in L)
>>> [xs for xs in L if len(xs[0]) == M]
[['largest', 'artlegs'], ['monster', 'sternom']]
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • Thank you so much! I had one more question. What if there were multiple sublists with longest of the same length? How would I get it to print the multiple sublists out? – joe smite Dec 11 '14 at 04:04
  • You can alwyas [flatten](http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python) your list before processing its values. – Marcin Dec 11 '14 at 04:06