gpt4 book ai didi

python - 使用python检查列表中是否存在元素

转载 作者:行者123 更新时间:2023-11-28 20:26:09 25 4
gpt4 key购买 nike

我是 python 的新手,想知道是否有人可以帮助我解决这个问题。我想看看 b 中的元素是否在 a 中。这是我的尝试。目前我没有得到任何输出。任何帮助将不胜感激,谢谢!

a = [1]
b = [1,2,3,4,5,6,7]

for each in b:
if each not in a == True:
print(each + "is not in a")

最佳答案

您正在测试两个不同的事物,结果为 False; Python 是 chaining the operators , 有效地测试 (each is in a) and (a == True):

>>> 'a' in ['a'] == True
False
>>> ('a' in ['a']) and (['a'] == True)
False
>>> ('a' in ['a']) == True
True

无论如何,您永远不需要在 if 语句上测试 True:

if each not in a:

足够了。

关于python - 使用python检查列表中是否存在元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12464254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com