-2

I need help in some basic python scrips, well I want to order a prayer in words from longer to shorter length and without repeating, until then everything is fine, what happens is that I do not know how to do to order words of the same length alphabetically.

KC.
  • 2,981
  • 2
  • 12
  • 22
  • 2
    Use `sort` with multiple keys, `s = sorted(s, key = lambda x: (len(x), x[0]))` – Rocky Li Nov 04 '18 at 23:14
  • File "test21.py", line 3 list.sort(key = len x: (len(x), x[0])) , reverse=True) ^ SyntaxError: invalid syntax – GosuBoostedAF Nov 04 '18 at 23:58
  • `key = lambda`, not `len` – Rocky Li Nov 05 '18 at 00:00
  • I don't do well, I order them well until I get to those that are the same size and those alphabetically order but the other way around, ie the word that begins with a is the last instead of the first. https://gyazo.com/6fbd4cae7f9a1f9836e62881cf7833dd – GosuBoostedAF Nov 05 '18 at 00:08
  • I see your problem - it's more complicated if you want one set of key to be positive and another to be reversed, working on it. – Rocky Li Nov 05 '18 at 00:10

1 Answers1

0

Since you're asking for a case where the 2 iterators will not be of the same order, you'll have to do it differently. You can consult this question Sort by multiple keys using different orderings. But since it doesn't contain what you really wanted, I'll answer it here:

from itertools import groupby

s = ['ddd', 'bb', 'ab', 'aa', 'cc', 'dab']
l = [sorted(list(g)) for b, g in groupby(s, key=lambda x: len(x))] 
l = [e for x in l for e in x]
>>> l
['dab', 'ddd', 'aa', 'ab', 'bb', 'cc']

This sort by negative order for length but positive order for words. Explanation: the first list comprehension turns the list of string into a list of list that contain sorted lists (by alphanumeric) of strings of same length. The second list comprehension unwraps the list of list into one list.

Rocky Li
  • 5,641
  • 2
  • 17
  • 33