Skip to main content
 首页 » 编程设计

Python 命令有效,但为什么呢

2025年05月04日24artech

我有一个简单的 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",则它不起作用。

虽然这个函数完成了我想要它做的事情,但我觉得它不干净而且我不知道为什么“if n in a is 'True':”的行为不等于“if n”的 else 部分in a is not 'True':"函数。

有人能帮我理解一下吗?

请您参考如下方法:

使用 bool 值检查然后将其与字符串进行比较并不是一种非常 pythonic 的方式,因此最好这样做:

a = [1,2,3] 
b = [2,4,6] 
 
def union(x,y): 
    for v in y: 
        if v not in x: 
            x.append(v) 
    return x 
 
print union(a,b) 

或者:

a.extend(set(b).difference(set(a))) 
print a 
>>> [1, 2, 3, 4, 6] 

或者如果您不关心新对象的创建:

print list(set(a).union(b))