Python中无限元素列表的实现方法

WBOY
Release: 2016-06-16 08:42:45
Original
1683 people have browsed it

本文实例讲述了Python怎么实现无限元素列表的方法,具体实现可使用Yield来完成。

下面所述的2段实例代码通过Python Yield 生成器实现了简单的无限元素列表。

1.递增无限列表

具体代码如下:

def increment():
 i = 0
 while True:
  yield i
  i += 1
 
for j in increment():
 print i
 if (j > 10) : break

Copy after login

2.斐波那契无限列表

具体代码如下:

def fibonacci():
 i = j = 1
 while True:
  result, i, j = i, j, i + j
  yield result
 
for k in fibonacci():
 print k
 if (k > 100) : break
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!