You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么自定义Python实现的intersection交集函数输出结果不正确?

错误原因
  • 可变对象引用篡改原数据:Python中列表属于可变对象,代码中U = A的写法仅将变量U绑定到原列表A的内存地址,并未生成独立的新列表。后续执行U.append()操作时会直接修改原列表A的内容,导致交集函数执行时遍历的A已经不是初始定义的[1,2,4,6,7,8],而是被追加了3、5后的列表,最终交集结果不符合预期。
  • 全局变量使用不规范:代码将存储结果的U、I定义为全局变量,函数内部直接修改全局变量,不仅不符合函数封装的要求,多次调用函数时还会出现结果累加的问题。
修复方案

修改逻辑如下:

  1. 并集函数内初始化结果列表时,使用A.copy()生成原列表A的独立拷贝,避免修改原数据
  2. 将结果列表U、I移入对应函数内部定义,避免全局变量污染

修改后的完整代码:

A = [1,2,4,6,7,8]
B = [1,3,4,5,6]

# 计算A与B的并集
def union(A, B):
    U = A.copy()
    for element in B:
        if element not in A:
            U.append(element)
    print("The union of A and B is: ", U)
union(A, B)

# 计算A与B的交集
def inters(A, B):
    I = []
    for element in A:
        if element in B:
            I.append(element)
    print("The intersection of A and B is: ", I)
inters(A, B)

运行输出:

The union of A and B is:  [1, 2, 4, 6, 7, 8, 3, 5]
The intersection of A and B is:  [1, 4, 6]

内容的提问来源于stack exchange,提问作者Soham Mirikar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 08:57:02