導航:首頁 > 編程語言 > python生成奇數序列生成器

python生成奇數序列生成器

發布時間:2022-05-14 17:27:33

python 中關於filter函數問題求教

看文字的話會很亂,和圖一起看會好一點

首先,it是個生成器(_odd_iter),並使n=3,隨後,it作為一個生成器存在於filter對象中(迭代器),並使it為一個filter對象,經過循環,到達next語句,先計算it _odd_iter(生成器),生成了新的數之後,開始計算filter。第一次循環的時候第18行的代碼相當於 it = filter(_not_divisible(3), it ),等號右面的it還在等待next調用生成值,生成值之後,就將它代入為lambda的x中……第二次循環的時候第18行代碼變成 it = filter(_not_divisible(5), filter(_not_divisible(3), it ) ),同樣等號右面的it仍然在等待next調用生成新的值
我剛看這個教程,不知道對不對。。。

對了我看見有一個人問把代碼第18行改成 it = filter(lambda x: x % n > 0, it)

會失去過濾功能,我覺得,lambda是一個臨時函數,所以覺得像filter(div(5), filter(div(3), it))這種存在多個lambda臨時函數的話是很奇怪的,

在調試時,發現filter只檢測了一個n(最近被賦值的),相當於7%5,9%7這樣,因此失去過濾素數功能。模擬一下,在將要輸出5的時候,it = filter()的那行代碼變為:

it = filter(lambda x : x % n >0 , filter (lambda x : x % n > 0 , it ) ),it將值賦給x,但是,我覺得n被賦值時,會刷新其他lambda中的n,造成類似於 it =filter(lambda x : x % 5 >0 , filter (lambda x : x % 5 > 0 , it ) )的情況

❷ python生成器到底有什麼優點

1、節省資源消耗,和聲明序列不同的是生成器在不使用的時候幾乎不佔內存,也沒有聲明計算過程!
2、使用的時候,生成器是隨用隨生成,用完即刻釋放,非常高效!
3、可在單線程下實現並發運算處理效果,非常牛逼,這點不可小視,看看nginx epoll單線程承載的並發量比多線程還效率高很多,最底層就是這個原理!

❸ 用python實現隨機生成三個有十個元素的數組把三個合並成一個數組挑出其中的奇數和偶數沒有重復

#coding=utf-8
'''
Created on 2012-6-4

@author: Administrator
'''
import random

def test():
minNum = 0#隨機數起始
maxNum = 999999#隨機數最大
#隨機生成三個序列,且為整數
list1 = [random.randint(minNum, maxNum) for i in xrange(10)]
list2 = [random.randint(minNum, maxNum) for i in xrange(10)]
list3 = [random.randint(minNum, maxNum) for i in xrange(10)]
lastList = list1 + list2 + list3#合在一起
lastList = list(set(lastList))#去掉重復,利用set是無序不重復的

oddNumList = []#用於保存奇數序列
evenNumList = []#用於保存偶數

for num in lastList:
if num % 2 == 0:
evenNumList.append(num)
else:
oddNumList.append(num)
print u"奇數有:", oddNumList, "共%d個" % len(oddNumList)
print u"偶數有:", evenNumList, "共%d個" % len(evenNumList)

if __name__ == '__main__':
test()

❹ 關於python的遞歸生成器

加了點注釋,自己看吧,下次不要用圖片了,直接拷貝代碼吧

#-*-coding:cp936-*-

defflatten(nested):
try:
#這里首先檢查nested是否可迭代,不可迭代則拋出TypeError
forsublistinnested:
#可迭代,那麼遞歸,檢查sublist是否還可以迭代
forelementinflatten(sublist):
#這里的element必定不可迭代,已經完全展開,因此使用yield輸出,返回上層
#如果sublist是不可迭代的,那麼flatten(sublist)返回的生成器就只有一個數據,就是sublist
#yieldelement也相當於yieldsublist
#否則的話,flatten(sublist)返回的是展開的數據
yieldelement
exceptTypeError:
#nested不可迭代,直接返回上層即可
yieldnested

❺ python如何得到1~20的奇數列表與偶數列表

1『獲取奇數和偶數列表可以不用for循環的形式,使用一句列表表達式即可實現,方法如下,首先在按下開始菜單打開jupyternotebook:

❻ python問題: filter+無限生成器,循環filter

#Python2.x下需導入itertools庫的ifilter才能和python3.x的filter等效
importitertools
def_odd_iter():
n=1
whileTrue:
n=n+2
yieldn
def_not_divisible(n):
returnlambdax:x%n>0
defprimes():
yield2
it=_odd_iter()
whileTrue:
n=next(it)
yieldn
#it=itertools.ifilter(_not_divisible(n),it)
it=itertools.ifilter(lambdax,n=n:x%n>0,it)
forninprimes():
ifn<1000:
print(n)
else:
break

❼ python 3.x調用random庫,隨機生成三個0到100內的奇數

importrandom
t=[random.randint(0,49)*2+1forninrange(3)]
print(t)

❽ 怎麼用python隨機生成一組整數,把它們按照奇數和偶數來進行分組

❾ python生成器是怎麼使用的

生成器(generator)概念
生成器不會把結果保存在一個系列中,而是保存生成器的狀態,在每次進行迭代時返回一個值,直到遇到StopIteration異常結束。
生成器語法
生成器表達式: 通列表解析語法,只不過把列表解析的[]換成()
生成器表達式能做的事情列表解析基本都能處理,只不過在需要處理的序列比較大時,列表解析比較費內存。

Python

1
2
3
4
5
6
7
8
9
10
11

>>> gen = (x**2 for x in range(5))
>>> gen
<generator object <genexpr> at 0x0000000002FB7B40>
>>> for g in gen:
... print(g, end='-')
...
0-1-4-9-16-
>>> for x in [0,1,2,3,4,5]:
... print(x, end='-')
...
0-1-2-3-4-5-

生成器函數: 在函數中如果出現了yield關鍵字,那麼該函數就不再是普通函數,而是生成器函數。
但是生成器函數可以生產一個無線的序列,這樣列表根本沒有辦法進行處理。
yield 的作用就是把一個函數變成一個 generator,帶有 yield 的函數不再是一個普通函數,Python 解釋器會將其視為一個 generator。
下面為一個可以無窮生產奇數的生成器函數。

Python

1
2
3
4
5
6
7
8
9
10
11

def odd():
n=1
while True:
yield n
n+=2
odd_num = odd()
count = 0
for o in odd_num:
if count >=5: break
print(o)
count +=1

當然通過手動編寫迭代器可以實現類似的效果,只不過生成器更加直觀易懂

Python

1
2
3
4
5
6
7
8
9
10
11

class Iter:
def __init__(self):
self.start=-1
def __iter__(self):
return self
def __next__(self):
self.start +=2
return self.start
I = Iter()
for count in range(5):
print(next(I))

題外話: 生成器是包含有__iter()和next__()方法的,所以可以直接使用for來迭代,而沒有包含StopIteration的自編Iter來只能通過手動循環來迭代。

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

>>> from collections import Iterable
>>> from collections import Iterator
>>> isinstance(odd_num, Iterable)
True
>>> isinstance(odd_num, Iterator)
True
>>> iter(odd_num) is odd_num
True
>>> help(odd_num)
Help on generator object:

odd = class generator(object)
| Methods defined here:
|
| __iter__(self, /)
| Implement iter(self).
|
| __next__(self, /)
| Implement next(self).
......

看到上面的結果,現在你可以很有信心的按照Iterator的方式進行循環了吧!
在 for 循環執行時,每次循環都會執行 fab 函數內部的代碼,執行到 yield b 時,fab 函數就返回一個迭代值,下次迭代時,代碼從 yield b 的下一條語句繼續執行,而函數的本地變數看起來和上次中斷執行前是完全一樣的,於是函數繼續執行,直到再次遇到 yield。看起來就好像一個函數在正常執行的過程中被 yield 中斷了數次,每次中斷都會通過 yield 返回當前的迭代值。

yield 與 return
在一個生成器中,如果沒有return,則默認執行到函數完畢時返回StopIteration;

Python

1
2
3
4
5
6
7
8
9
10
11

>>> def g1():
... yield 1
...
>>> g=g1()
>>> next(g) #第一次調用next(g)時,會在執行完yield語句後掛起,所以此時程序並沒有執行結束。
1
>>> next(g) #程序試圖從yield語句的下一條語句開始執行,發現已經到了結尾,所以拋出StopIteration異常。
Traceback (most recent call last):
File "<stdin>", line 1, in <mole>
StopIteration
>>>

如果遇到return,如果在執行過程中 return,則直接拋出 StopIteration 終止迭代。

Python

1
2
3
4
5
6
7
8
9
10
11
12

>>> def g2():
... yield 'a'
... return
... yield 'b'
...
>>> g=g2()
>>> next(g) #程序停留在執行完yield 'a'語句後的位置。
'a'
>>> next(g) #程序發現下一條語句是return,所以拋出StopIteration異常,這樣yield 'b'語句永遠也不會執行。
Traceback (most recent call last):
File "<stdin>", line 1, in <mole>
StopIteration

如果在return後返回一個值,那麼這個值為StopIteration異常的說明,不是程序的返回值。
生成器沒有辦法使用return來返回值。

Python

1
2
3
4
5
6
7
8
9
10
11

>>> def g3():
... yield 'hello'
... return 'world'
...
>>> g=g3()
>>> next(g)
'hello'
>>> next(g)
Traceback (most recent call last):
File "<stdin>", line 1, in <mole>
StopIteration: world

生成器支持的方法

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

>>> help(odd_num)
Help on generator object:

odd = class generator(object)
| Methods defined here:
......
| close(...)
| close() -> raise GeneratorExit inside generator.
|
| send(...)
| send(arg) -> send 'arg' into generator,
| return next yielded value or raise StopIteration.
|
| throw(...)
| throw(typ[,val[,tb]]) -> raise exception in generator,
| return next yielded value or raise StopIteration.
......

close()
手動關閉生成器函數,後面的調用會直接返回StopIteration異常。

Python

1
2
3
4
5
6
7
8
9
10
11
12
13

>>> def g4():
... yield 1
... yield 2
... yield 3
...
>>> g=g4()
>>> next(g)
1
>>> g.close()
>>> next(g) #關閉後,yield 2和yield 3語句將不再起作用
Traceback (most recent call last):
File "<stdin>", line 1, in <mole>
StopIteration

send()
生成器函數最大的特點是可以接受外部傳入的一個變數,並根據變數內容計算結果後返回。
這是生成器函數最難理解的地方,也是最重要的地方,實現後面我會講到的協程就全靠它了。

Python

1
2
3
4
5
6
7
8
9
10
11
12
13

def gen():
value=0
while True:
receive=yield value
if receive=='e':
break
value = 'got: %s' % receive

g=gen()
print(g.send(None))
print(g.send('aaa'))
print(g.send(3))
print(g.send('e'))

執行流程:
通過g.send(None)或者next(g)可以啟動生成器函數,並執行到第一個yield語句結束的位置。此時,執行完了yield語句,但是沒有給receive賦值。yield value會輸出初始值0注意:在啟動生成器函數時只能send(None),如果試圖輸入其它的值都會得到錯誤提示信息。
通過g.send(『aaa』),會傳入aaa,並賦值給receive,然後計算出value的值,並回到while頭部,執行yield value語句有停止。此時yield value會輸出」got: aaa」,然後掛起。
通過g.send(3),會重復第2步,最後輸出結果為」got: 3″
當我們g.send(『e』)時,程序會執行break然後推出循環,最後整個函數執行完畢,所以會得到StopIteration異常。
最後的執行結果如下:

Python

1
2
3
4
5
6
7

0
got: aaa
got: 3
Traceback (most recent call last):
File "h.py", line 14, in <mole>
print(g.send('e'))
StopIteration

throw()
用來向生成器函數送入一個異常,可以結束系統定義的異常,或者自定義的異常。
throw()後直接跑出異常並結束程序,或者消耗掉一個yield,或者在沒有下一個yield的時候直接進行到程序的結尾。

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

def gen():
while True:
try:
yield 'normal value'
yield 'normal value 2'
print('here')
except ValueError:
print('we got ValueError here')
except TypeError:
break

g=gen()
print(next(g))
print(g.throw(ValueError))
print(next(g))
print(g.throw(TypeError))

輸出結果為:

Python

1
2
3
4
5
6
7
8

normal value
we got ValueError here
normal value
normal value 2
Traceback (most recent call last):
File "h.py", line 15, in <mole>
print(g.throw(TypeError))
StopIteration

解釋:
print(next(g)):會輸出normal value,並停留在yield 『normal value 2』之前。
由於執行了g.throw(ValueError),所以會跳過所有後續的try語句,也就是說yield 『normal value 2』不會被執行,然後進入到except語句,列印出we got ValueError here。然後再次進入到while語句部分,消耗一個yield,所以會輸出normal value。
print(next(g)),會執行yield 『normal value 2』語句,並停留在執行完該語句後的位置。
g.throw(TypeError):會跳出try語句,從而print(『here』)不會被執行,然後執行break語句,跳出while循環,然後到達程序結尾,所以跑出StopIteration異常。
下面給出一個綜合例子,用來把一個多維列表展開,或者說扁平化多維列表)

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

def flatten(nested):

try:
#如果是字元串,那麼手動拋出TypeError。
if isinstance(nested, str):
raise TypeError
for sublist in nested:
#yield flatten(sublist)
for element in flatten(sublist):
#yield element
print('got:', element)
except TypeError:
#print('here')
yield nested

L=['aaadf',[1,2,3],2,4,[5,[6,[8,[9]],'ddf'],7]]
for num in flatten(L):
print(num)

如果理解起來有點困難,那麼把print語句的注釋打開在進行查看就比較明了了。

總結
按照鴨子模型理論,生成器就是一種迭代器,可以使用for進行迭代。
第一次執行next(generator)時,會執行完yield語句後程序進行掛起,所有的參數和狀態會進行保存。再一次執行next(generator)時,會從掛起的狀態開始往後執行。在遇到程序的結尾或者遇到StopIteration時,循環結束。
可以通過generator.send(arg)來傳入參數,這是協程模型。
可以通過generator.throw(exception)來傳入一個異常。throw語句會消耗掉一個yield。可以通過generator.close()來手動關閉生成器。
next()等價於send(None)

❿ 在Python里使用for…in循環完成10開始的奇數序列水平列印,最大數不超過200

閱讀全文

與python生成奇數序列生成器相關的資料

熱點內容
java聊天窗口 瀏覽:976
單片機控制陣列led燈 瀏覽:577
白鹿用的什麼APP修圖 瀏覽:499
阿里雲輕量應用伺服器ssh無法連接 瀏覽:794
員工福利系統源碼 瀏覽:982
數據加密如何設置 瀏覽:570
php取余運算 瀏覽:153
php如何壓縮圖片大小 瀏覽:137
編程三階教程 瀏覽:983
pdf顏色查看 瀏覽:469
怎麼用指令停用命令方塊java 瀏覽:406
滑鼠命令行 瀏覽:567
如何朗讀pdf 瀏覽:746
壓縮機啟動後繼電器發燙 瀏覽:405
小學編程項目學習 瀏覽:557
net編譯運行原理 瀏覽:786
加密電腦的文件拷出來打不開 瀏覽:366
可達性演算法根 瀏覽:208
ibm的伺服器怎麼安裝系統 瀏覽:492
pdftomobi在線 瀏覽:797