过去几天我一直在玩python而且我一直遇到一个奇怪的问题。 (作为参考,我正在研究项目euler的345.) 所以......我试图将一个二维阵列的一行和一列归零,但不是它们相交的点。现在,我明白可能有更多的pythonic方法来解决这个问题,但我主要关注为什么我这里的代码不起作用。
library(tibble)
library(purrr)
t(all) %>%
as_tibble() %>%
reduce(intersect)
无论如何,我希望函数输出为
def choose(initial_grid,row,col):
"""Return a grid with a given row and column zeroed except where intersect.
"""
grid = list(initial_grid) #FLAG 1
Special_value = grid[row][col]
grid[row] = [0]*len(grid[row])
for i in xrange(len(grid)):
grid[i][col] = 0
grid[row][col] = Special_value
return grid
qwer = [[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9,10,11,12],
[13,14,15,16]]
print choose(qwer,1,1)
print qwer
但是......事实并非如此。无论出于何种原因,[[1, 0, 3, 4], [0, 6, 0, 0], [9, 0, 11, 12], [13, 0, 15, 16]]
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
都会清除其第1列。我已经尝试使用列表副本取消引用qwer
传递的指针,我尝试使用initial_grid,
,但似乎没有任何效果。
那有什么不对?我该如何解决?为什么这是错的?
答案 0 :(得分:1)
list(initial_grid)
会对您的列表进行浅层复制。内部列表不会被复制。
演示:
>>> l = [[1, 2], [0, 0]]
>>> c = list(l)
>>> l is c
False
>>> all(x is y for x,y in zip(l, c))
True
>>> c[0][0] = 5
>>> c
[[5, 2], [0, 0]]
>>> l
[[5, 2], [0, 0]]
如果您需要深层副本,请使用copy.deepcopy
。或者对于2D列表,写
>>> d = [sub[:] for sub in l]
>>> d[0][0] = 7
>>> d
[[7, 2], [0, 0]]
>>> l
[[5, 2], [0, 0]]
另外,你的术语已关闭。我们没有Python的指针。我们有名字和价值观。