尝试执行布尔 AND 时出现类型错误



我正在尝试学习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函数在这种情况下工作,以查看如果两个列表是否所有项目都相等,但我想知道三个项目中的两个是否相等,而第三个不相等。

谢谢。

你使用的是单个 & 符号,而不是在最后的 if 语句中and

if guesses[0] in favorite and guesses[1] in favorite and 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.')

单个 & 符号表示按位,它是在二进制类型上完成的,而不是布尔值,这是您需要的。


顺便说一句(如果这对您的程序很重要(,值得注意的是,这仅检查guesses列表的一种排列(即,如果guesses[0]不在favourites而不是guesses[2]中怎么办?

虽然可能不是最有效或最优雅的,但您可以通过mapsum来实现这一点:

# Turns each element of guesses into 1 if it's in favourites or 0 if not.
in_favourites = map(lambda x: 1 if x in favourites else 0, guesses)
# Sum the list of 1's and 0's
number_in_favourites = sum(in_favourites)
# Do your check (you could do number_in_favourites >= 2)
if number_in_favourites == 2:
print("Woopee!")
# Or more concisely:
if sum(map(lambda x: x in favourites, guesses)) == 2:
print("Woopee!")

(免责声明,我纯粹是在浏览器中编写此代码,所以我还没有测试过它,但它应该大致是这样的!

相关内容

最新更新