Python 3.6 / my函数改变了我的全局变量

时间:2017-03-31 10:11:05

标签: python-3.x

我正在努力使我的功能不要弄乱我的全局'b'值,因为我希望在使用集合的另一个类似函数中重用该列表,但似乎即使不使用相同的名称(y),它们(b和y)仍然绑在一起......

大多数打印行仅用于调试,因为我不了解发生了什么。

我做错了什么?

import random

a = random.sample(range(1,25),8)
b = random.sample(range(1,25),11)
a.sort()
b.sort()

def list_rdup(x,y):
    print('Loop remove duplicates:')
    print('x:',x)
    print('y:',y)
    for i in x:
        y.append(i)
    y.sort()
    print('y modified:',y)
    c = []
    for i in y:
        if i in c:
            pass
        else: 
            c.append(i)
    return c

print('a:',a)
print('b:',b)

print(list_rdup(a,b))

print('a:',a)
print('b:',b)

输出:我们看到a和b处于原始状态..然后我运行函数和 再次打印a和b以显示b在此过程中被修改...

a:[1,6,10,11,12,13,17,22]

b:[1,2,3,7,13,16,17,19,20,21,24]

循环删除重复项:

x:[1,6,10,11,12,13,17,22]

y:[1,2,3,7,13,16,17,19,20,21,24]

y修改:[1,1,2,3,6,7,10,11,12,13,13,16,17,17,19,20,21,22,24]

[1,2,3,6,7,10,11,12,13,16,17,19,20,21,22,24]

a:[1,6,10,11,12,13,17,22]

b:[1,1,2,3,6,7,10,11,12,13,13,16,17,17,19,20,21,22,24]

2 个答案:

答案 0 :(得分:0)

调用list_rdup(a,b)只传递存储在x和y中的a和b的引用。因此,x和y的任何变化都会改变a和b。如果您不希望a和b更改,请使用b_copy = b.copy()

答案 1 :(得分:-1)

要避免更改元素,请复制数组。

import random

a=[1, 6, 10, 11, 12, 13, 17, 22]
b=[1, 2, 3, 7, 13, 16, 17, 19, 20, 21, 24]
#a.sort()
#b.sort()

def list_rdup(x,y):
    print('Loop remove duplicates:')
    print('x:',x)
    print('y:',y)
    for i in x:
        y.append(i)
    y.sort()
    print('y modified:',y)
    c = []
    for i in y:
        if i in c:
            pass
        else: 
            c.append(i)
    return c

print('a:',a)
print('b:',b)

print(list_rdup(a[:], b[:]))

print('a:',a)
print('b:',b)
a: [1, 6, 10, 11, 12, 13, 17, 22]
b: [1, 2, 3, 7, 13, 16, 17, 19, 20, 21, 24]
Loop remove duplicates:
x: [1, 6, 10, 11, 12, 13, 17, 22]
y: [1, 2, 3, 7, 13, 16, 17, 19, 20, 21, 24]
y modified: [1, 1, 2, 3, 6, 7, 10, 11, 12, 13, 13, 16, 17, 17, 19, 20, 21, 22, 24]
[1, 2, 3, 6, 7, 10, 11, 12, 13, 16, 17, 19, 20, 21, 22, 24]
a: [1, 6, 10, 11, 12, 13, 17, 22]
b: [1, 2, 3, 7, 13, 16, 17, 19, 20, 21, 24]

如果数组中有非原始值,也请考虑深度复制。