【问题标题】:TypeError when trying to do a Boolean AND尝试执行布尔 AND 时出现 TypeError
【发布时间】: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,位运算符是&amp;。所以你想要guesses[0] in favorite and guesses[1] in favorite
  • 与问题无关,但为什么只打印games 的前 8 个元素?就像您没有显示 'God of War''Spider-Man' 但这些是您的最爱?这个程序似乎有点作弊......
  • 谢谢大家的帮助。 Tadhg 我选择在打印列表时对其进行切片,并在打印列表的其余部分之前添加一个新行,因为它会继续运行而不是换行。
  • 您的索引无处不在

标签: python bitwise-operators logical-operators


【解决方案1】:

您在最后的 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] 中怎么办? )

虽然可能不是最高效或最优雅的,但您可以通过 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!")

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

【讨论】:

  • 谢谢 th3ant,你已经彻底回答了我的问题,并且给了我更多的阅读时间来做哈哈。再次感谢。
猜你喜欢
  • 2020-05-10
  • 2017-10-17
  • 1970-01-01
  • 2022-10-21
  • 2013-07-11
  • 2011-11-18
  • 2014-11-11
  • 2016-05-25
  • 1970-01-01
相关资源
最近更新 更多