我想隐藏或不隐藏list3
背后的字母" *"在list2
中,取决于所选字母是否在list1
中。但是,我的列表理解不起作用。
我在Python 3中的代码:
list1 = [ "h", "e", "l", "l", "o"]
list2 = ["h", "*", "*", "*", "o"]
letter_chosen = input("Choose a letter: ")
list3 = [letter_chosen for letter in list1 if letter_chosen == letter else letter2 for letter2 in list2]
在Python解释器中,如果我输入" l"作为letter_chosen
,我想:
list3 = ["h", "*", "l", "l", "o"]
感谢您的帮助。
答案 0 :(得分:1)
您的语法无效;你不能一次循环两个列表。尝试使用zip
命令:
>>> list(zip(list1, list2))
[('h', 'h'), ('e', '*'), ('l', '*'), ('l', '*'), ('o', 'o')]
它会将两个列表中的项目配对。所以,你的表达式变成:
>>> list3 = [letter_choosen if letter_choosen == letter1 else letter2 for (letter1, letter2) in zip(list1, list2)]
>>> list3
['h', '*', 'l', 'l', 'o']
答案 1 :(得分:1)
如果你开始写出一个正常的循环,那会更容易。
你想这样做:
for letter in list1:
if letter_choosen == letter:
letter # picked letter, so add it to the output
else:
# not the picked letter, use the value from letter2 at the same position
从list2获取值的最简单方法是使用zip()
;这将两个列表中的值配对:
for letter, letter2 in zip(list1, list2):
if letter_choosen == letter:
letter # picked letter, so add it to the output
else:
letter2 # not the picked letter, copy over the one from list2
请注意if
测试要添加的值,因此它是表达式的一部分。您可以改为使用条件表达式:
for letter, letter2 in zip(list1, list2):
letter if letter_choosen == letter else letter2
然后可以将其转换为列表理解:
[letter if letter_choosen == letter else letter2 for letter, letter2 in zip(list1, list2)]
或使用更紧凑和易于理解的变量名称:
goal = ["h", "e", "l", "l", "o"]
display = ["h", "*", "*", "*", "o"]
guess = input ("Choose a letter: ")
new_display = [g if guess == g else d for g, d in zip(goal, display)]
答案 2 :(得分:-1)
您可以这样做:
[letter if letter_choosen != letter else '*' for letter in list1]