如何对迭代器进行切片操作
test = list ( range ( 10 ) )
res1 = test. __getitem__( 0 )
print ( res1)
res2 = test. __getitem__( slice ( 0 , 2 ) )
print ( res2)
from itertools import islice
res3 = islice( test, 0 , 4 )
print ( res3)
res4 = islice( test, 0 , 4 , 1 )
print ( res4)
res5 = islice( test, 0 , 4 , 2 )
print ( res5)
如何在for循环中迭代多个可迭代对象
from random import randint
test1 = list ( randint( 0 , 10 ) for _ in range ( 10 ) )
test2 = list ( randint( 10 , 20 ) for _ in range ( 10 ) )
test3 = list ( randint( 20 , 30 ) for _ in range ( 10 ) )
print ( test1)
print ( test2)
print ( test3)
test = [ ]
for res1, res2, res3 in zip ( test1, test2, test3) :
test. append( res1 + res2 + res3)
print ( test)
from itertools import chain
demo = [ x for x in chain( test1, test2, test3) if x % 2 == 0 ]
print ( demo)
如何派生内置不可变类型并修其改实例化行为
class IntTuple ( tuple ) :
def __new__ ( cls, iterable) :
demo = ( i for i in iterable if isinstance ( i, int ) and i > 0 )
return super ( ) . __new__( cls, demo)
test = IntTuple( [ - 2 , - 4 , - 5 , 0 , 0.2 , 8 , 9 ] )
print ( test)
如何创建可管理的对象属性
class Student ( ) :
def __init__ ( self, score) :
self. score = score
@property
def value ( self) :
return self. score
@value. setter
def value ( self, score) :
if not isinstance ( score, int ) :
raise TypeError( "wrong type" )
self. score = score
test = Student( 66 )
print ( test. value)
test. value = 88
print ( test. value)