# Python实现动态规划时，[None for i in range(len(B))]和[None]*len(B)得出不同结果

shengwubin
• 227
``````def lcs_memo(x, y, i, j, c):
if i < 0 or j < 0:
return 0
if c[i][j] is None:
if x[i] == y[j]:
c[i][j] = lcs_memo(x, y, i - 1, j - 1, c) + 1
else:
c[i][j] = max(lcs_memo(x, y, i - 1, j, c), lcs_memo(x, y, i, j - 1, c))
return c[i][j]``````

``````A = 'abccc'
B = 'cccba'
C = [[None for j in range(len(B))] for i in range(len(A))]
print(lcs_memo(A, B, len(A) - 1, len(B) - 1, C))``````

``````A = 'abccc'
B = 'cccba'
C = [[None] * len(B)] * len(A)
print(lcs_memo(A, B, len(A) - 1, len(B) - 1, C))``````

``````C = [[None for j in range(len(B))] for i in range(len(A))]
C = [[None] * len(B)] * len(A)``````

2 个回答
✓ 已被采纳

``````>>> b = [[0,0]] * 3
>>> b[0][0] = 4
>>> b
[[4, 0], [4, 0], [4, 0]]``````
``````>>> c = [[0, 0] for i in range(3)]
>>> c[0][0] = 4
>>> c
[[4, 0], [0, 0], [0, 0]]``````

``````>>> e = [0] * 3
>>> e[0] = 4
>>> e
[4, 0, 0]``````

``````l = [[]] * 5
print([id(x) for x in l]) # [2337055020296, 2337055020296, 2337055020296, 2337055020296, 2337055020296]``````

``````l = [[] for x in range(5)]
print([id(x) for x in l]) # [2337054512712, 2337055068872, 2337055068360, 2337055020168, 2337055019528]``````

###### 你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进