Discuss / Python / 大佬们求救

大佬们求救

Topic source

Eye丶杯

#1 Created at ... [Delete] [Delete and Lock User]
def triangles():
    n = [1]
    while True:
        yield n
        n = [x+y for x,y in zip([0] + n,n+[0])]

在百度上找到这样一种解法

但是我没有看懂

 zip函数打包后的元组中元素为什么可以调用出来 

其中的x,y表示的是什么

阮神奇

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

我也是初学者,就用老师的原话回答你把

面的for循环里,同时引用了两个变量,在Python里是很常见的,比如下面的代码:

>>> for x, y in [(1, 1), (2, 4), (3, 9)]:
...     print(x, y)
...
1 1
2 4
3 9

下面是我搜的zip函数用法

以下实例展示了 zip 的使用方法:

>>>a = [1,2,3]>>> b = [4,5,6]>>> c = [4,5,6,7,8]>>> zipped = zip(a,b) # 打包为元组的列表
[(1, 4), (2, 5), (3, 6)]>>> zip(a,c) # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]>>> zip(*zipped) # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式
[(1, 2, 3), (4, 5, 6)]

结合起来看就懂了

Eye丶杯

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

感谢

理解了 我后面自己试了一下 x,y就是zip之后里面(,)有两个元素的元组


  • 1

Reply