c语言函数生成器,生成器以及内置函数

本文详细讲解了生成器的创建方法,包括生成器函数、推导式和内置函数,以及yield的使用、返回值和next操作。此外,还介绍了列表推导式、字典推导式、生成器表达式等Python高级数据结构的用法,涉及匿名函数、内置函数特性和字符串处理。

生成器的初始

生成器构建方式

通过生成器函数(自己写的函数)

通过生成器推导式

通过python内置的函数或者模块提供(python提供的生成器函数)

def func():

print(111)

return 2

ret = func()

print(ret)

执行此函数,遇到return结束函数。

将数字2返回给ret。

def func():

print(111)

print(111)

print(111)

print(111)

print(111)

print(111)

yield 2,4,5

yield 3

yield 4

yield 5

ret = func() # 生成器对象

print(ret) #

'''

类比

l1 = [2,] [2,3,4,5]

obj = iter(l1)

'''

只要函数中出现了yield那么他就不是函数,它是生成器函数。

一个next对应一个yield.

print(next(ret))

print(next(ret))

print(next(ret))

print(next(ret))

print(next(ret))

print(next(ret))

return yield

return 结束函数,给函数的执行者返回值(多个值通过元组的形式返回)。

yield 不结束函数,对应着给next返回值(多个值通过元组的形式返回)。

举例说明:

def eat_baozi():

list1 = []

for i in range(1,2001):

list1.append(f'{i}号包子')

return list1

print(eat_baozi())

def eat_baozi_gen():

for i in range(1,2001):

print(11)

yield f'{i}号包子'

'''

ret1 = eat_baozi_gen()

ret2 = eat_baozi_gen()

print(ret1)

print(ret2)

print(next(ret1))

print(next(ret1))

print(next(ret1))

print(next(ret2))

print(next(ret2))

print(next(ret2))

print(next(ret))

print(next(ret))

'''

ret = eat_baozi_gen()

for i in range(200):

print(next(ret))

for i in range(200):

print(next(ret))

yield from

def func():

l1 = [1, 2, 3]

yield l

ret = func()

print(next(ret))

print(next(ret))

print(next(ret))

def func():

l1 = [1, 2, 3]

yield from l1

'''

yield 1

yield 2

yield 3

'''

ret = func()

print(next(ret))

print(next(ret))

print(next(ret))

yield : 对应next给next返回值

yield from 将一个可迭代对象的每一个元素返回给next

yield from 节省代码,提升效率(代替了for循环)

l1 = [1,2,3......100]

l1 = []

for i in range(1,101):

l1.append(i)

print(l1)

列表推导式

l1 = [i for i in range(1, 101)]

print(l1)

两种构建方式:

1.循环模式: [变量(加工后的变量) for 变量 in iterable]

2.筛选模式: [变量(加工后的变量) for 变量 in iterable if 条件]

循环模式:

将10以内所有整数的平方写入列表。

print([i**2 for i in range(1, 11)])

100以内所有的偶数写入列表.

print([i for i in range(2, 101, 2)])

从python1期到python100期写入列表list

print([f'python{i}期' for i in range(1, 101)])

2.筛选模式:

print([i for i in range(1, 101) if i > 49])

三十以内可以被三整除的数。

print([i for i in range(1, 31) if i % 3 == 0])

过滤掉长度小于3的字符串列表,并将剩下的转换成大写字母

l1 = ['barry', 'fdsaf', 'alex', 'sb', 'ab']

print([i.upper() for i in l1 if len(i) > 3])

找到嵌套列表中名字含有两个‘e’的所有名字(有难度)

names = [['Tom', 'Billy', 'Jefferson', 'Andrew', 'Wesley', 'Steven', 'Joe'],

['Alice', 'Jill', 'Ana', 'Wendy', 'Jennifer', 'Sherry', 'Eva']]

l1 = []

for i in names:

for j in i:

if j.count('e') > 1:

l1.append(j)

print(l1)

print([j for i in names for j in i if j.count('e') > 1])

列表推导式的优缺点:

优点:

# 1, 简单,快捷,装b。

缺点:

# 2. 可读性不高,不好排错。

慎用,不要入迷。

生成器表达式:

与列表推导式几乎一模一样。

循环模式,筛选模式。

obj = (i for i in range(1, 11))

# print(obj)

# print(next(obj))

# print(next(obj))

# print(next(obj))

# print(next(obj))

# print(next(obj))

# print(next(obj))

# print(next(obj))

# print(next(obj))

# print(next(obj))

# print(next(obj))

# print(next(obj))

# 如何触发生成器(迭代器)取值?

1. next(obj)

2. for 循环

# for i in obj:

# print(i)

3. 数据转化

print(list(obj))

生成器表达式:生成器 节省内存。

字典推导式,集合推导式: 两种模式: 循环模式,筛选模式

l1 = ['小潘', '怼怼哥','西门大官人', '小泽ml亚']

{0: '小潘', 1: '怼怼哥', 2: '西门大官人'}

dic = {}

for index in range(len(l1)):

dic[index] = l1[index]

print(dic)

print({i:l1[i] for i in range(len(l1))})

1~100

print({i for i in range(1, 101)})

匿名函数:没有名字的函数

匿名函数只能构建简单的函数,一句话函数。

def func(x,y):

return x + y

print(func(1, 2))

匿名函数构建

func2 = lambda x,y: x + y

print(func2(1, 2))

匿名函数最常用的就是与内置函数结合使用。

写匿名函数:接收一个可切片的数据,返回索引为 0与2的对应的元素(元组形式)。

func = lambda x: (x[0],x[2])

print(func('太白金星'))

写匿名函数:接收两个int参数,将较大的数据返回。

func1 = lambda x, y: x if x > y else y

print(func1(100,2))

func2 = lambda : 3

print(func2())

str() dir() range() len() print() max() min() open()input() type() int() enumerate() list() id() set() dict()iter() next() tuple() bool() globals() locals() frozenset()

eval exce

慎用

s1 = "{1: 'alex'}"

s2 = '1 + 3'

eval 剥去字符串的外衣,返回里面的本质

ret = eval(s1)

print(ret,type(ret))

print(eval(s2))

exec 代码流,过程。

s3 = '''

for i in range(3):

print(i)

'''

exec(s3)

s3 = input('>>>')

print(eval(s3))

hash()

print(hash(123214134))

print(hash('fkljdsaklgjdfs'))

print(hash('gjdfs'))

help()

print(help(str.count))

callable **

def a():

pass

b = 3433

a()

b()

print(callable(a))

print(callable(b))

int **

print(int(3.14))

print(int('123'))

print(float(100))

print(complex(1,2))

print(bin(100)) # 将十进制转化成二进制。 print(oct(10)) # 将十进制转化成八进制字符串并返回。

print(hex(17)) # 将十进制转化成十六进制字符串并返回。

print(hex(15))

计算除数与被除数的结果,返回一个包含商和余数的元组(a // b, a % b)分页用到

print(divmod(10, 3)) # **

保留小数的有效位置

print(round(3.1485926,2))

print(pow(3, 3)) # 333

print(pow(3, 3, 2))

输入字符寻找其在unicode的位置。

print(ord('a'))

print(ord('中'))

输入位置数字找出其对应的字符

print(chr(98)) # **

print(chr(20104)) # 予

repr 原形毕露 **

print('太白')

print(repr('太白'))

msg = '我叫%r' %('太白')

print(msg)

all any **

0,'',[],{},set(),(),None

l1 = [1, 'fgdsa', [], {1: 2}]

l2 = [0, '', [], {}]

print(all(l1)) # 判断可迭代对象元素全部都为True,返回True

print(any(l2)) # 判断可迭代对象元素只要有一个True返回True

sep 设定分割符。

end 默认是换行可以打印到一行

print(1, 2, 3, sep='|')

print(1, 2, end=' ')

print(3, 4)

f = open('log','w',encoding='utf-8')

# f.write('写入文件')

print('写入文件', file=f)

list

l1 = list('fdsafd')

print(l1)

dict

创建字典的几种方式

dic = {1: 2}

# 字典推导式

# print({i: 1 for i in range(3)})

# dict()

dic = dict(one=1, two=2, three=3)

print(dic)

# fromkeys()

abs() 获取绝对值

print(abs(-10))

sum() 数字相加求和

sum(iterable,)

print(sum([1,2,3,4]))

print(sum([1, 2, 3, 4], 100))

非常非常非常重要的

min 可以加功能

print(min([22, 11, 45, 2]))

l1 = [('alex', 73, 170), ('太白', 18, 185), ('武大', 35, 159),]

# l1 = [(73, 'alex'), (35, '武大'), (18, '太白')]

# 找年龄最小的元组

# print(min(l1))

# 通过设置key去使用min

# key = 函数名

# def func(x): # x = ('alex', 73)

# return x[1]

# 返回值是什么就按照什么比较最小的。

# min 会自动的将可迭代对象的每一个元素作为实参传给x,

'''

第一次,x = ('alex', 73) 73

第二次,x = ('武大', 35) 35

第三次,x = ('太白', 18) 18

'''

将遍历的那个元素即是 ('太白', 18) 返回

print(min(l1,key=func))

print(min(l1,key=lambda x: x[1]))

def func(x):

return x[1]

print(min(l1,key=func))

print(min(l1,key=lambda x: x[1]))

print(min(l1,key=lambda x: x[2])[0])

a = 1

练习:

dic = {'a':3,'b':2,'c':1}

将dic值最小的键返回。

print(min(dic,key= lambda x:dic[x]))

# 将dic值最小的值返回。

print(dic[min(dic,key= lambda x:dic[x])])

dic = {'A':['李业', 67],'b': ['怼哥', 95],'c': ['冯垚', 85]}

# 将成绩最低的从属于的那个列表返回。

print(dic[min(dic,key=lambda x:dic[x][1])])

# 将成绩最低的分数返回。

print(dic[min(dic,key=lambda x:dic[x][1])][1])

max() 与min 相同。

reversed() 对一个可迭代对象进行翻转,返回一个迭代器

s1 = 'alex'

# print(reversed(s1))

for i in reversed(s1):

print(i)

内置函数:bytes()

s1 = '太白'

方法一:

print(s1.encode('utf-8'))

方法二:

print(bytes(s1,encoding='utf-8'))

解码:

b1 = b'\xe5\xa4\xaa\xe7\x99\xbd'

# 方法一:

# print(b1.decode('utf-8'))

# 方法二:

print(str(b1, encoding='utf-8'))

标签:内置,函数,生成器,ret,next,yield,l1,print,dic

来源: https://www.cnblogs.com/-777/p/11061193.html

AutoFlowchart Version 2.4.3 ------------------------------------ what's is AutoFlowchart? -------------------------------------------------------------------- AutoFlowchart, the Professional sourcecode flowcharting tool. AutoFlowchart is a excellent tool to generate flowchart from sourcecode.Its flowchart can expand and shrink. and you can pre-define the the width , height,Horizontal spacing and vertical spacing. Move and zoom is also very easy. It can export the flowchart as a Microsoft Visio/Word file or a bitmap file. It can help programmers understand, document and visualize source code. It supports C,C++,VC++(Visual C++ .NET),Delphi(Object Pascal). In the future,It will support more languages. You can use it on Windows 9X/NT/me/XP. You can trial it for 50 times. Registration fee is $129. http://www.ezprog.com/order.htm what's new? -------------------------------------------------------------------- v2.4.3 [2008-07-12] 1. Add process to "return","continue" and "break"; 2. Revised the color when export to coloried Ms Word file; v2.4.1 [2008-04-21] 1. Add "read only" options; 2. Change multi language captions for "open project" and "save project"; v2.4 [2008-04-02] 1. Add "project" to AutoFlowchart to manage more files; v2.3 [2008-01-14] 1. auto show a detail code ; 2. use GDI+ to draw flowchart and draw text; 3. add search function; 4. change the arrowhead shape; 5. remove a bug when in Windows Server 2003; v2.0.3 [2007-12-06] 1. It's use a SDI window for flowchart instead of MDI, then it would be possible to display the code window on one monitor while displaying the flowchart on a second monitor! Thanks for Mr. Shahine Ghanbarzadeh! v2.0.2 [2007-11-29] 1. Add treatment to exceptional such as unmatched brackets. 2. Add treatment to special function which lines is more than 1000. Ms Visio is supported! Get Started -------------------------------------------------------------------- 1. Open a *.pas/*.c/*.cpp/*.afp file; 2. Double click the begin row of any statement ,then you can see a flowchart; 3. Click a apart of the FlowChart ,you can see the part of sentence of this block; 4. change the value of the first spinedit,you can see the current block. Register Notes: If you are a registered user, please put the license file to the install path. Check out our WWW Home Page: http://www.ezprog.com AutoFlowchart can be ordered for $79 from: CompuServe: ShareIt (#197238) Direct: http://www.shareit.com/product.html?productid=197238&languageid=1 Contact -------------------------------------------------------------------- support : support@ezprog.com sales : sals@ezprog.com Msn : support@ezprog.com _______ ____|__ | (R) --| | |------------------- | ____|__ | Association of | | |_| Shareware |__| o | Professionals -----| | |--------------------- |___|___| MEMBER
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值