Python 列表在嵌套循环中奇怪地修改自身
问题发生在嵌套循环中。在第一次迭代中,一切都很好。在i上的第二次迭代也会修改第一个列表,以此类推。二维列表中的零应该是对角的Python 列表在嵌套循环中奇怪地修改自身,python,Python,问题发生在嵌套循环中。在第一次迭代中,一切都很好。在i上的第二次迭代也会修改第一个列表,以此类推。二维列表中的零应该是对角的 import math def calcpyth(p1, p2): distance = math.sqrt(((p1[0] - p2[0]) ** 2) + ((p1[1] - p2[1]) ** 2)) return distance tuple0 = (42, 288) tuple1 = (45, 326) tuple2 = (50, 364) t
import math
def calcpyth(p1, p2):
distance = math.sqrt(((p1[0] - p2[0]) ** 2) + ((p1[1] - p2[1]) ** 2))
return distance
tuple0 = (42, 288)
tuple1 = (45, 326)
tuple2 = (50, 364)
tuple3 = (57, 400)
list = [tuple0, tuple1, tuple2, tuple3]
zeros = [[0]*len(list)]*len(list)
test = zeros
for i in range(len(test)):
for j in range(len(test)):
test[i][j] = calcpyth(list[i], list[j])
问题就在眼前
zeros = [[0]*len(list)]*len(list)
在该行代码中,您创建了两个列表:
[0]*len(list)
zeros = [[0 for lv in range(len(list))] for lv in range(len(list))]
一般建议:尽量不要覆盖内置函数,如
list
。。。一个典型的命名约定是调用您自己的列表list\uu