Reputation: 47
python beginner here. According to this thread,, I learned how to access values of tuples inside lists.
This is the answer in the thread above:
[x[1] for x in L]
I have a list of tuples here:
[('w', False), ('o', True), ('r', False), ('d', False)]
I would like to read the True/False value in each tuple and print an underscore if the value is false and print the character if the value is true. For example, in the above list, since 'o'
is the item that is True, I would like to print _o__
.
This is what I have been trying so far, and I feel like I'm in the right direction, but since I'm writing this thread, it obviously doesn't work:
for char in word: #part i need help on
if [x[1] for x in word] == True:
print("_", end="")
elif [x[1] for x in word] == False:
print(word[char], end="")
This is the entire code if more info is needed (beginnings of a Hangman game, long way to go), but specifically I need help with the above block of code:
randomword = "word" #will add random words when it works properly
word = [(char, False) for char in randomword] #splits randomword into list of tuples of different characters with a false value assigned because no letters have been guessed yet
def getLetter(): #letter guessing function, limits input to one character
guess = input("Guess a letter: ")
if len(guess) != 1 or (guess.isalpha()) == False:
while len(guess) != 1 or (guess.isalpha()) == False:
print("Must be" + "\033[96m one letter!" + "\033[0m Try again.")
guess = input("Guess a letter: ")
return guess
guess = getLetter()
for char in range(word.__len__()):
if word[char][0] == guess.lower():
word[char] = (guess, True) #a correct guess changes the False to True
print(word)
for char in word: #part i need help on
if [x[1] for x in word] == True:
print("_", end="")
elif [x[1] for x in word] == False:
print(word[char])
Upvotes: 1
Views: 458
Reputation: 717
Using List comprehension this can be done as :
word = [('w', False), ('o', True), ('r', False), ('d', False)]
new_word = [elements[0] if elements[1]==True else "_" for elements in word]
for element in new_word:
print(element,end="")
Here turn-by-turn elements of a list are extracted and as it is a tuple that has two elements their 1st index is checked for true or false and depending upon the value either character or _ is assigned, which is done using the ternary operator in python.
Upvotes: 1
Reputation: 5889
I would say you kind of overcomplicated that. Instead try something like this.
lst = [('w', False), ('o', True), ('r', False), ('d', False)]
for tup in lst:
if tup[1] == True:
print(tup[0],end="")
elif tup[1] == False:
print('_', end="")
Upvotes: 2