签名分隔函数覆盖在列表中传递而不是返回新的

时间:2014-08-18 23:07:40

标签: python

我正在编写一个函数,它接收带有正数和负数的数据集,并希望有两个函数将列表分成正数或负数,并用零替换你不想要的那个。但是我的代码覆盖了原来的列表。

CODE:

##
# Data Sign Separator
##

def positive_data(data):

    #Takes in data and returns data with all negative numbers set to zero

    #holds positive data
    positive = data

    for indx, val in enumerate(positive):
        if(val<0):
            positive[indx] = 0

    return positive

def negative_data(data):

    #Takes in data and returns data with all positive numbers set to zero

    #holds positive data
    negative = data

    for indx, val in enumerate(negative):
        if(val>0):
            negative[indx] = 0

    return negative

test = [1,-1,2,-2,3,-3,4,-4,5,-5,6,-6,7,-7,8,-8]

print "original"
print test
print "positive"
print positive_data(test)
print "negative"
print negative_data(test)

输出:

original
[1, -1, 2, -2, 3, -3, 4, -4, 5, -5, 6, -6, 7, -7, 8, -8]
positive
[1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8, 0]
negative
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

正如你可以看到积极的功能起作用,但负面的功能似乎已经从正面功能中得到了输入....

当我首先运行否定函数时,正函数得到完全相反的结果:

CODE:

test = [1,-1,2,-2,3,-3,4,-4,5,-5,6,-6,7,-7,8,-8]

print "original"
print test
print "negative"
print negative_data(test)
print "positive"
print positive_data(test)

输出:

original
[1, -1, 2, -2, 3, -3, 4, -4, 5, -5, 6, -6, 7, -7, 8, -8]
negative
[0, -1, 0, -2, 0, -3, 0, -4, 0, -5, 0, -6, 0, -7, 0, -8]
positive
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

2 个答案:

答案 0 :(得分:2)

代码:

new_list = old_list

不会复制列表,它会创建另一个指向同一列表的名称。所以当你改变一个时,另一个也会改变。要复制列表,您应该使用:

new_list = old_list[:]

实施例

>>> old_list = [0, 0, 0]
>>> not_new_list = old_list     # another name for the same list
>>> not_new_list[0] = 1
>>> print old_list
[1, 0, 0]

>>> old_list = [0, 0, 0]
>>> new_list = old_list[:]      # the list is copied in new_list
>>> not_new_list[0] = 1
>>> print old_list
[0, 0, 0]

答案 1 :(得分:1)

使用列表推导可以轻松实现您正在尝试编写的内容:

>>> l = list(range(-10,10)) # python3
>>> l
[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [x if x > 0 else 0 for x in l]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [x if x < 0 else 0 for x in l]
[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

它根据现有列表生成新列表。您正在做的是为同一列表positive = data创建一个新名称,该列表不会复制,因此您可以在现有列表上进行操作。