Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replacing list items that fit condition in lambda

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.

like image 703
Nakle Avatar asked Jun 06 '17 00:06

Nakle


2 Answers

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
like image 151
MSeifert Avatar answered Nov 10 '22 15:11

MSeifert


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", "_", "_"]
like image 5
Ajax1234 Avatar answered Nov 10 '22 14:11

Ajax1234