我有一个简单的代码,在Python中是这样的:
a = [1,2,3]
b = [2,4,6]
def union(a,b):
pos = 0
while pos < len(b):
n = b[pos]
if n in a is not 'True':
a = a
else:
a.append(n)
pos = pos +1
return a
print union(a,b)
如您所见,第一个IF语句毫无意义。但是,如果我这样编码:
if n in a is 'True':
a.append(n)
它不起作用。第一个代码段更改a=[1,2,4,6]—只添加列表“b”中不在列表“a”中的数字。如果我按照建议将“If”代码段更改为“is”“True”,它将不起作用。你知道吗
虽然这个函数做了我想做的事情,但我觉得它不干净,我不知道为什么“if n in a is'True':”的行为不等于“if n in a is not'True':”函数的其他部分。你知道吗
有人能帮我理解吗?你知道吗
使用布尔检查并将其与字符串进行比较不是一种非常适合的方法,因此最好这样做:
或:
或者,如果您不关心新对象的创建,请执行以下操作:
您应该只使用
True
,而不是字符串'True'
或者更好,只是
如果您是初学者,您可能没有意识到Python有一个名为^{} 的内置类型
set
对象已经有了交集/并集等方法in
和is
/is not
都是关系运算符,在Python中,关系运算符是链接的。因此n in a is not 'True'
等价于n in a and a is not 'True'
,n in a is 'True'
等价于n in a and a is 'True'
。很明显,它们不是相互否定的,因为它们都有n in a
。你知道吗但是不要使用
is
,除非你知道你需要它,也不要和布尔值比较(除非yadda yadda)。你知道吗相关问题 更多 >
编程相关推荐