I've been stuck on a line of my code for a while, and I'm at a loss as to why it returns as it does.
guess = 'a'
word = ['a', 'b', 'c']
board = ['_', '_', '_']
board = list(map(lambda x: guess if word[board.index(x)] == guess else x, board))
print(board)
This returns
['a', 'a', 'a']
Whereas my goal is a return of
['a', '_', '_']
My previous solution was to loop through the list with an increasing value for the index, and to individually check each entry in word against the guess, and to replace the board list at the same index, but I feel that there is a more concise and pythonic way using lambda
, I just can't quite get it.
The problem is the list.index
method which returns the index of the first match:
list.index(x[, start[, end]])
Return zero-based index in the list of the first item whose value is x. Raises a
ValueError
if there is no such item. [...]
If you're also interested in a solution: You could 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 could also use a normal for
-loop. That way you would avoid creating and discarding lists all the time:
for idx, char in enumerate(word):
if char == guess:
board[idx] = char
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", "_", "_"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With