我正在尝试学习python,但遇到了一些练习代码。我想检查一下我放入名为guesses
的列表中的三个项目中的两个是否在另一个名为favorite
的列表中,同时查看是否要放入列表{{ 1}}不在其他列表guesses
中。
favorite
我的问题是我认为我上面的if语句可以工作,请有人解释为什么我在下面收到此TypeError:
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.')
我还理解 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'
函数在这种情况下可以工作,以查看两个列表是否相等是否所有项目,但我想知道三个项目中的两个是否相等而第三个项目不相等。
谢谢。
答案 0 :(得分:2)
您在最终的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.')
单个&号表示bitwise and是在二进制类型上完成的,而不是boolean and是您所需的。
顺便说一句(如果这对您的程序很重要),值得注意的是,这仅检查guesses
列表中的一个排列(即,如果guesses[0]
不在favourites
中怎么办而不是guesses[2]
?)
虽然可能不是最高效或最优雅的,但您可以使用map
和sum
来实现:
# 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!")
(免责声明,我纯粹是在浏览器中编写此代码,因此我尚未对其进行测试,但应该大致如此!)