简体   繁体   English

Python循环不会给出预期的输出

[英]Python looping doesn't give expected output

I am trying to find the missing elements between arr1 and arr2 but not sure what's the issue with the code, why it's not working. 我试图找到arr1和arr2之间缺少的元素,但不确定代码的问题是什么,为什么它不起作用。 Please suggest. 请建议。

def miss2(arr1, arr2):
    arr3=arr1
    for i in arr1:
        # print(i)
        for j in arr2:
            # print(i,j)
            if i == j:
                arr3.remove(j)

    print(arr3)

arr1=[1,2,3,4]
arr2=[1,2]

miss2(arr1,arr2)

result: [2, 3, 4] instead of [3, 4] 结果: [2, 3, 4]而不是[3, 4]

Objects in Python are stored by reference ,which means you didn't assign the value of arr1 to arr3 , but a pointer to the object.You can use is operator to test if two objects have the same address in memory. Python中的对象通过引用存储,这意味着您没有将arr1的值赋给arr3 ,而是指向该对象的指针。您可以使用is运算符来测试两个对象是否在内存中具有相同的地址。

Sequences can be copied by slicing so you can use this to copy a list: 可以通过切片复制序列,以便您可以使用它来复制列表:

arr3 = arr1[:]

Also you can use 你也可以使用

arr3 = list(arr1)

Or you can use copy() module: 或者你可以使用copy()模块:

from copy import copy
arr3 = copy(arr1)

By the way,you can try this: 顺便说一下,你可以试试这个:

print [i for i in arr1 if i not in arr2]

McGrady is right. 麦格雷迪是对的。 Here is an article tells you more stuff about the reference problem. 这篇文章告诉你有关引用问题的更多内容。 Is Python call-by-value or call-by-reference? Python是按值调用还是按引用调用?

And you can use "set"(consider the math concept) data structure instead of "list", here: 你可以使用“set”(考虑数学概念)数据结构而不是“list”,这里:

x = set([1,2,3,4])
y = set([1,2])
x - y

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM