Replacing list items that match a condition in lambda

I’ve been stuck in a line of my code for some time, and I don’t understand why it returns like him.

guess = 'a' word = ['a', 'b', 'c'] board = ['_', '_', '_'] board = list(map(lambda x: guess if word[board.index(x)] == guess else x, board)) print(board) 

It returns

 ['a', 'a', 'a'] 

While my goal is return

 ['a', '_', '_'] 

My previous solution was to iterate over the list with an increasing value for the index and individually check each entry in the word against the guess and replace the list of boards in the same index, but I feel that there is a more concise and pythonic way using lambda , I just I can’t get it.

+5
source share
4 answers

The problem is the list.index method , which returns the index of the first match :

list.index(x[, start[, end]])

Returns an index with a zero index in the list of the first element whose value is x . Raises a ValueError if there is no such element. [...]

If you are also interested in a solution: you can simply iterate over both word and board :

 guess = 'a' word = ['a', 'b', 'c'] board = ['_', '_', '_'] board = list(map(lambda x, y: guess if x == guess else y, word, board)) # 3 parameters! print(board) # ['a', '_', '_'] 

Given that you want to replace, you can also use regular for -loop. This way you avoid creating and dropping lists all the time:

 for idx, char in enumerate(word): if char == guess: board[idx] = char 
+5
source

You can use list comprehension:

 guess = 'a' word = ['a', 'b', 'c'] new_word = [i if i == guess else "_" for i in word] 

This will give you:

 ["a", "_", "_"] 
+5
source

You are probably looking for something like this:

 board=map(lambda x: x[1] if x[1] == guess else board[x[0]], enumerate(word)) 
+3
source

You can use list comprehension as indicated in the answers, but in your code the board will always be reset with every guess. I assume that you want to track guesses until all letters are guessed (or until the number of guesses), so your loop should have a temporary list and then loop through the board to add new guesses (if found) something like:

 word = ['a', 'b', 'c'] board = ['_', '_', '_'] tries = 0 while tries != 3: guess = raw_input("Enter a guess: ") tmp = [x if x == guess else '_' for x in word] for i in xrange(len(board)): if board[i] == '_': try: board[i] = tmp[i] except IndexError: pass print(board) if '_' not in board: print('Solved!') break tries += 1 if tries == 3: print('Not solved!') 
0
source

Source: https://habr.com/ru/post/1268572/


All Articles