Home > Software design >  Sort a list according to the indexes of a string
Sort a list according to the indexes of a string

Time:05-19

How to make the elements entered in a list have the same index as those of a given word?

In this case it is a mystery word chosen at random in a game of hangman.

It could look like this (that's just a code portion that I take but the problem is right here):

import random
    
WORDS = ('Fire', 'Wind', 'Water', 'Earth')
word = random.choice(WORDS)
letters = []
    
while len(letter) != len(word):
    aletter = input('choose a letter...') 
    if aletter in word and len(aletter) == 1:
        for i in range(len(word)):
            letter.append(aletter)

I don't know how to say that each element added to the list will not be put in disorder but will be put in order even if we type it before the first letter in the input aletter.

For example if the word is Wind and I send 'i' (which is in the word) before 'W', but I enter 'W' after it then 'i' will be appended before 'W' instead of ['W', 'i'] (The normal order would be ['W', 'i', 'n', 'd'] but with this problem the letters could be totally reversed depending on the order they are appended. I figured it had something to do with the index of the elements.

So here's what I tried to say in a way:

"This list (letters) will rearrange itself according to the indexes of the elements in word."

letters[i] = word[k]

This example above is with a double loop, one for aletter and one for word, the indexes are i and k.

letters.insert(i, aletter)

In this one I want to insert all aletter in index of word, at the position i.

letters.index(aletter) == i

And finally in this one I want each index of the entered elements to be equal to those of word.

I converted the list in a string to compare them, but my problem is how to sort this list first.

CodePudding user response:

IIUC, you may want to use some placeholders, e.g. underscores, for the letters that have not been guessed yet. For example:

import random

WORDS = ('Fire', 'Wind', 'Water', 'Earth')
word = random.choice(WORDS)
letters = ['_' for letter in word]

while '_' in letters:
    print(''.join(letters))
    aletter = input('choose a letter...') 
    if aletter in word and len(aletter) == 1:
        for i, c in enumerate(word):
            if aletter == c:
                letters[i] = c     

CodePudding user response:

You can use the build in function sort it works for strings to.

 my_list = ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']
 my_list.sort()
  • Related