1.定义一个生成器函数,生成1-10
使用next(generator)方法获取1-10
使用for循环获取
def get_num():
for num in range(1, 11):
yield num
gen = get_num()
print(type(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
<class 'generator'>
1
2
3
4
5
6
7
8
9
10
2.# 自己定义一个MyIterator, 实现range的功能
# range(start, stop, step) => MyIterator
# range(10) # start=0, stop=10, step=1
# rang(10) # range(start=0, stop, step=1) =>start=10
# range(0,10)
# range(0,10,2)
# MyIterator(10)
# MyIterator(0,10)
# MyIterator(0,10,2)
class MyIterator:
def __init__(self, start=None, stop=None, step=1):
#传递一个参数
if start is not None and stop is None:
self.stop = start
self.start = 0
#传递两个参数, 三个参数
if start is not None and stop is not None:
self.start = start
self.stop = stop
self.step = step
def __iter__(self):
return self
def __next__(self):
#什么时候取完了,需要一个终止的条件
#需要有一个记录位置的变量, 如果这个位置超过 stop结束
if self.start < self.stop:
data = self.start
self.start += self.step
return data
else:
raise StopIteration
for i in MyIterator(10):
print(i)
for i in MyIterator(1, 10):
print(i)
for i in MyIterator(1, 10, 2):
print(i)
0
1
2
3
4
5
6
7
8
9
1
2
3
4
5
6
7
8
9
1
3
5
7
9
- re中函数的使用(自己写用例来使用):
match
fullmatch
search
findall
finditer
split
sub
subn
complie
import re
pattern = "hello"
string = "hello world"
result = re.match(pattern, string)
print(result, type(result))
<re.Match object; span=(0, 5), match='hello'> <class 're.Match'>
import re
pattern = "hello"
string = "hello"
match_obj = re.fullmatch(pattern, string)
print(match_obj)
<re.Match object; span=(0, 5), match='hello'>
pattern = "hello"
string = "world hello"
match_obj = re.search(pattern, string)
print(match_obj)
<re.Match object; span=(6, 11), match='hello'>
string3 = "hello world hello"
pattern = "hello"
result = re.findall(pattern, string3)
print(result)
['hello', 'hello']
string = "hello world hello"
pattern = "hello"
result = re.finditer(pattern, string)
print(result)
<callable_iterator object at 0x000002922BB52BE0>
string = "计算机,软件,网络"
pattern = ","
result = re.split(pattern, string, maxsplit=1)
print(result)
['计算机', '软件,网络']
result = re.sub(",", "-", "计算机,软件,网络")
print(result)
result = re.sub(",", "-", "计算机,软件,网络", 1)
print(result)
计算机-软件-网络
计算机-软件,网络
result = re.subn(",", "-", "计算机,软件,网络", 1)
print(result)
result = re.subn(",", "-", "计算机,软件,网络",)
print(result)
('计算机-软件,网络', 1)
('计算机-软件-网络', 2)
string = "hello world hello"
pattern = "hello"
compile_obj = re.compile(pattern)
print(compile_obj.search(string))
print(compile_obj.findall(string))
print(compile_obj.match(string))
<re.Match object; span=(0, 5), match='hello'>
['hello', 'hello']
<re.Match object; span=(0, 5), match='hello'>