我目前有一个二维矩阵
matrix = [['.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.'],
['.', '.', '.', 'O', 'O', 'O'],
['.', '.', '.', 'O', '.', '.'],
['.', '.', '.', 'O', 'O', '.']]
Run Code Online (Sandbox Code Playgroud)
我已指定copy = matrix
制作矩阵的副本。但是,我遇到了一个错误,当我修改 时copy[]
,它也会修改matrix[]
. 我发现这是别名的副作用,我需要创建matrix[]
.
如何在不使用导入的情况下创建二维矩阵的深层副本?
我创建了一个代码,用于在音乐列表 ( music_list
) 中挑选随机音乐并将它们添加到music_queue
. 当我执行这段代码时,所有的元素music_list
都被删除了,我不明白为什么。
print("Music list lenght : " + str(len(music_list)))
if len(music_queue) == 0:
tmp = music_list
while len(tmp) > 0:
music_queue.append(tmp.pop(randint(0,len(tmp) - 1)))
print("Music list lenght : " + str(len(music_list)))
Run Code Online (Sandbox Code Playgroud) 我来自 R,正在尝试更好地掌握可变性。下面是代码,我认为我理解其中的前两部分(请参阅评论)。我不明白第三部分。
#1. Refering to same instance with two variable names
listOrig = [i for i in range(1001, 1011)]
listCopy = listOrig
listOrig[0]=999
listOrig == listCopy #Returns True, because both variable names actually refer
#to the same instance, ergo still containing the same values
listOrig[0] is listCopy[0] #Same instance 999, the id is also the same as a
#consequence
#2. Refering to same part of original list through slicing
listSlice = listOrig[0:5]
listOrig[0] is listSlice[0] #Returns True, analogous to above …
Run Code Online (Sandbox Code Playgroud) 如何不更改列表的值???
>>> a=range(0,5)
>>> b=10
>>> c=a
>>> c.append(b)
>>> c
[0, 1, 2, 3, 4, 10]
>>> a
[0, 1, 2, 3, 4, 10]
Run Code Online (Sandbox Code Playgroud)
直到今天我还不知道python中的列表是可变的!
我有这个代码:
x = 'x'
y = []
y.append(x)
z = y
z.append('a')
x = 'X'
print "x:", x
print "y:", y
print "z:", z
Run Code Online (Sandbox Code Playgroud)
输出:
x: X
y: ['x', 'a']
z: ['x', 'a']
Run Code Online (Sandbox Code Playgroud)
我知道这是正确的输出,但我很难理解它产生的原因
y: ['x', 'a']
Run Code Online (Sandbox Code Playgroud)
代替
y: ['x']
Run Code Online (Sandbox Code Playgroud) 如果我在Python 2.7中运行以下代码,我会为a和b打印[2.,2.,2.].为什么b与a一起变化?非常感谢!
def test_f(x):
a = np.zeros(3)
b = a
for i in range(3):
a[i] += x
print a
print b
return 0
test_f(2)
Run Code Online (Sandbox Code Playgroud) 我来自java世界,我期待以下事情
int a = valueassignedbyfunction();
int b = a;
a = a + 1;
Run Code Online (Sandbox Code Playgroud)
在此之后a大于b.但是在python中,一旦a = a + 1操作完成,b就会自动增加1,因为这个b引用的是同一个对象.如何只复制a的值并将其分配给名为b的新对象?
谢谢!