我无法理解ans = [[None] * R for _ in range(C)] and ans = [[None] * R] * C
当我在自爆代码中使用第一个ans
时,结果是[[1,4],[2,5],[3,6]]
,结果是我想要的,但是使用第二个ans
则使每一行具有相同的列表,例如
[[3, 6], [3, 6], [3, 6]]
有人知道为什么吗?
class Solution():
def transpose(self, A):
R = len(A)
C = len(A[0])
ans = [[None] * R for _ in range(C)]
# ans = [[None] * R] * C
for r in range(R):
for c in range(C):
ans[c][r] = A[r][c]
return ans
if __name__ == "__main__":
A = [[1,2,3],[4,5,6]]
ans = [[1,4],[2,5],[3,6]] # the target result
print(Solution().transpose(A))