在生成器中附加项目以在 Python 中列出时出现奇怪的外观

  • 本文关键字:外观 项目 Python python
  • 更新时间 :
  • 英文 :


我试图使用以下代码生成一个 p 级帕斯卡三角形:

def triangles(p):
    L = [1]
    count = 0
    while count < p:
        yield L
        L.append(0)
        L = [L[i - 1] + L[i] for i in range(len(L))]
        count = count + 1
def pascal(p):
    result = []
    t = triangles(p)
    for i in range(p):
        result.append(next(t))
    return result

pascal(5( 的预期结果应该是

[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]],但我得到了 [[1, 0], [1, 1, 0], [1, 2, 1, 0], [1, 3, 3, 1, 0], [1, 4, 6, 4, 1, 0]] 代替。

我尝试在三角形(5(中打印每个i,

for i in triangles(5):
    print i

结果是:

[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]

然后我尝试了:

result = []
for i in triangles(5):
    print result
    print i
    result.append(i)
    print result

输出如下所示:

[] # result in step 1, before append
[1] # 1st item in triangles(5)
[[1]] # result in step 1, after append
[[1, 0]] # result in step 2, before append, here's where it changes
[1, 1]
[[1, 0], [1, 1]]
[[1, 0], [1, 1, 0]]
[1, 2, 1]
[[1, 0], [1, 1, 0], [1, 2, 1]]
[[1, 0], [1, 1, 0], [1, 2, 1, 0]]
[1, 3, 3, 1]
[[1, 0], [1, 1, 0], [1, 2, 1, 0], [1, 3, 3, 1]]
[[1, 0], [1, 1, 0], [1, 2, 1, 0], [1, 3, 3, 1, 0]]
[1, 4, 6, 4, 1]
[[1, 0], [1, 1, 0], [1, 2, 1, 0], [1, 3, 3, 1, 0], [1, 4, 6, 4, 1]]

为什么追加会更改列表中的前一个值?

L.append(0)生成

列表后更改列表,因为python中的对象是共享的。

尝试

L = L + [0]

而是创建新列表,而不是就地更改它。

最新更新