【发布时间】:2020-04-05 02:39:12
【问题描述】:
我正在尝试学习 python,但我被一些练习代码卡住了。我想检查我放入名为guesses 的列表中的三个项目中的两个是否在另一个名为favorite 的列表中,同时检查我放入列表中的第三个项目guesses 是否不在另一个列表favorite。
games = ['CS:GO', 'MK11', 'Black Ops 3', 'League of Legends', 'Osu!', 'Injustice 2', 'Dont Starve', 'Super Smash Brothers: Ultimate', 'God of War', 'Kingdom Hearts 3', 'Red Dead Redemption 2', 'Spider-Man', ]
favorite = ['God of War', 'CS:GO', 'Spider-Man']
guesses = ['', '', '']
print('I like ' + str(len(games) + 1) + ' games and here there are:' + str(games[:8]) + '\n' + str(games[9:]))
print('Can you guess whats are my favorite three games out of my list?')
guesses[0] = input()
print('Whats game number 2?')
guesses[1] = input()
print('Whats game number 3?')
guesses[2] = input()
# if all(x in favorite for x in guesses):
# print('Yes! Those are my three favorite games!')
if guesses[0] in favorite & guesses[1] in favorite & guesses[2] not in favorite:
print('Sorry, ' + str(guesses[0]) + ' & ' + str(guesses[1]) + ' are two of my favorite games but unfortunately ' + str(guesses[2]) + ' is not.')
我的问题是我认为我上面的 if 语句会起作用,请有人解释一下为什么我在下面得到这个 TypeError:
line 18, in <module>
if guesses[0] in favorite & guesses[1] in favorite & guesses[2] not in favorite:
TypeError: unsupported operand type(s) for &: 'list' and 'str'
我也知道all 函数在这种情况下可以查看两个列表是否相等,但我想知道三个项目中的两个是否相等,而第三个不相等。
谢谢。
【问题讨论】:
-
在python中布尔AND运算符使用单词
and,位运算符是&。所以你想要guesses[0] in favorite and guesses[1] in favorite -
与问题无关,但为什么只打印
games的前 8 个元素?就像您没有显示'God of War'或'Spider-Man'但这些是您的最爱?这个程序似乎有点作弊...... -
谢谢大家的帮助。 Tadhg 我选择在打印列表时对其进行切片,并在打印列表的其余部分之前添加一个新行,因为它会继续运行而不是换行。
-
您的索引无处不在
标签: python bitwise-operators logical-operators