This question already has answers here:
python: changes to my copy variable affect the original variable [duplicate]
(4个答案)
2年前关闭。
希尔伯特矩阵是一个方阵,其元素由下式给出:
A[i][j]= 1 / (i+j+1)
我的代码是:
def Hilbert(n):
H = [[0]*n]*n
for i in range(n):
for j in range(n):
H[i][j] = 1/(i+j+1)
return H
例如对于n = 3,它应该返回
[1, 1/2, 1/3]
[1/2, 1/3, 1/4]
[1/3, 1/4, 1/5]
但它返回3行
[1/3, 1/4, 1/5]
我的错在哪里?
python参考方案
当你做
H = [[0]*n]*n
最后一个*n
制作第一个[0 0 0 .... (n)]
列表的浅表副本。通过修改第一列中的任何元素,可以更改所有列(列表内的项目是对第一列的引用)。
Numpy对数组操作很有用,但是如果您不想使用它,请尝试
H = [[0]*n for i in xrange(n)]
要查看是否有指向相同整数的元素,可以尝试
for i in range(n):
for j in range(n):
print(id(H[i][j])) # [id() is the memory address](https://docs.python.org/2/library/functions.html#id)
另外:使用numpy的是
H = np.zeros((n, n))
参考:https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.zeros.html
Python:检查新文件是否在文件夹中[重复] - pythonThis question already has answers here: How do I watch a file for changes? (23个答案) 3年前关闭。 我是python的新手,但是我尝试创建一个自动化过程,其中我的代码将侦听目录中的新文件条目。例如,某人可以手动将zip文件复制到一个特定的文件夹中,并且我希望我的代码能够在文件完全…
从文件中读取用户名和密码[重复] - pythonThis question already has answers here: How to read a file line-by-line into a list? (28个答案) 2年前关闭。 如何在Python中逐行读取文本(例如用户名和密码)?例如,我可以在shell / bash中实现此目的:#!/bin/bash AUTH='/aut…
python切片的奇怪行为[重复] - pythonThis question already has answers here: Reversing a list slice in python (2个答案) 7个月前关闭。 假设我们有以下列表:>>> a = [x for x in range(10)] >>> print(a) [0, 1, 2, 3, 4, 5, 6…
为随机选择的变量分配一个值[重复] - pythonThis question already has answers here: How do I randomly select a variable from a list, and then modify it in python? …
Python sqlite3数据库已锁定 - python我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…