If speed is important and your list of words is even moderately long, you are probably better off making a lookup rather than searching for the index of each character for each word.
You can use the string function translate()
and maketrans()
to create a fast way of converting the input strings to a translation for sorting.
For example:
# make translation table
trans = str.maketrans(g, "".join(sorted(g)))
# translate words works like:
"revestir".translate(trans) # 'ivevhgri'
# sort with it:
sorted(l, key=lambda word: word.translate(trans))
# ['revestir', 'miel', 'extraterrestre', 'auto', 'automovil', 'al']
This also has the benefit of being resilient to errors if there are characters in your strings that are not in your alphabet, which index()
will choke on. They just get passed through, like:
"reve*stir".translate(trans)
# 'ivev*hgri'