python-3.x - 列表发生了变异,但我没有直接对其进行变异
问题描述
在我的代码中,我尝试获取列表中元素的每个组合(我不想使用 itertools)。我通过用二进制计数来做到这一点,True
然后False
我将其应用于原始列表以获取所有组合(如果为真,则该数字将保留在非列表中,它将被删除)。现在我分配x
了 0 所以[False, False, ...]
在循环中,二进制数被添加。现在的问题是,如果我想将列表重置为 0,它不会改变,只是继续使用之前的列表。例如,在print(x)
它打印的第一个代码中:[False,False,False,False,False,False,False,False,],[True,False,False,False,False,False,False,False,],[True,True,False,False,False,False,False,False,], ...]
. 我可以打印x
或test
打印相同的结果,但我没有更改 x。有任何想法吗?
def get_combinations(arr):
true = []
x = []
for thing in range(0,len(arr)):
true.append(thing)
x.append(False)
true.sort(reverse=True)
test = []
final = []
länge = 2**len(arr)
for number in range(länge):
test = x <------------------------------- here
#print(x) or print(test)
for thing in true:
if number / (2**thing) >= 1:
test[thing] = True
number -= 2**thing
final.append(test)
return final
test = [1,2,4,5,3,1,5,13]
get_combinations(test)
如果我将行更改为:
test = [False,False,False,False,False,False,False,False]
它工作正常。
解决方案
查找“Python 中的深拷贝与浅拷贝”
简而言之 :
x= [1,2,3]
如果:
y = x # x: [1,2,3] , y: [1,2,3]
y[0] = 4 # x: [4,2,3] , y: [4,2,3]
-- 请注意,y = x
'y' 和 'x' 设置为相等,但更重要的是,'x' 和 'y' 是同一个对象……任何一个变化都会改变另一个。所以y[0] = 4
也影响了谢x[0] is also now 4
。
另一方面 :
y = x.copy() # x: [1,2,3] , y: [1,2,3]
y[0] = 4 # x: [1,2,3] , y: [4,2,3]
-- 这里 'y' 与 'x' 具有相同的值,但它们是不同的对象。通过更改 yy[0] = 4
不会影响“x”。
在您的代码中:
test =x
和后面的'test'元素被修改,改变'x',然后在下一次迭代中,'x'for loop
不再是[False,False...]
将该行替换为:
test =x.copy()
推荐阅读
- python-3.x - scipy k-means算法不使用所有k
- python - 如何从他的多对多关系中选择包含某些孩子的父母?
- heroku - 重复后 Tweepy Bot 崩溃
- elasticsearch - 千分尺与公制节拍
- javascript - Javascript 正则表达式未显示与 Python 中相同的结果
- python - 在 pandas 列中提取正则表达式
- css - SCSS 明暗主题色,如何才能发挥作用?
- javascript - Chrome 扩展程序清单版本 3 中的内容安全策略
- sql - 使用 SELECT INTO 进行多表查询
- c++ - << 和 >> 对 c++ 中 ostream/istream 类的 cout /cin 对象有什么作用?