Discuss / Python / 练习

练习

Topic source

风袭6729

#1 Created at ... [Delete] [Delete and Lock User]

def triangles(): a = [1]; while True: yield a a = [sum(i) for i in zip([0] + a, a + [0])]

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]

不错,代码很简洁

Danny丶杨

#3 Created at ... [Delete] [Delete and Lock User]

能详细讲解一下吗?这个练习不太明白,谢谢啦!

liadbiz

#4 Created at ... [Delete] [Delete and Lock User]

写了个长一点的...不过没用到生成器。

在此插入代码

def triangles(): a = [1] while 1: yield a A = a + [0] A = [0] + a a = [ ] for i in range(0, len(A)): a.append(A[i] + A[i])

请问While True 是根据什么判断的?

廖雪峰

#6 Created at ... [Delete] [Delete and Lock User]

while True是死循环

第二次迭代后都是从循环开始执行,不再执行a = [1]的吗?

Geek_MrHowe

#8 Created at ... [Delete] [Delete and Lock User]

学习笔记: 感觉风袭6729写的代码比我简洁一万倍 特来学习

def triangles():
    a = [1];
    while True:
        yield a
        a = [sum(i) for i in zip([0] + a, a + [0])]

一步步理解过程 首先 [0] + a和a + [0]是在原list上左边和右边都加一个0元素; 比如a=[1, 2, 1]时 [0] + a》》[0,1, 2, 1] a + [0]》》[1, 2, 1,0] 然后重要的是函数zip了,之前没见过的。百度了下,他的作用如下

x = [1, 2, 3]

y = [4, 5, 6]

z = [7, 8, 9]

xyz = zip(x, y, z)

print xyz

得到结果是:

[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

所以当a=[1, 2, 1]时,zip([0] + a, a + [0])得到的是

[(0,1), (1, 2),(2, 1), (1,0)]

所以[sum(i) for i in zip([0] + a, a + [0])]等价于 [sum(i) for i in [(0,1), (1, 2),(2, 1), (1,0)]]

看了你们的评论会了一点,谢谢诸君。

厉害呀


  • 1
  • 2

Reply