打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
python中推导式创建序列

推导式创建序列

  • 列表推导式
  • 字典推导式
  • 集合推导式

推导式是从一个或者多个迭代器快速创建序列的一种方法。它可以将循环和条件判断结合,从而避免冗长的代码。推导式是典型的Python风格,会使用它代表你已经超过Python初学者的水平。

列表推导式

列表推导式生成列表对象,语法如下:
[表达式 for item in 可迭代对象]
或者:{表达式 for item in 可迭代对象 if 条件判断}

>>>[xforxinrange(1,5)][1,2,3,4]>>>[x*2forxinrange(1,5)][2,4,6,8]>>>[x*2forxinrange(1,20)ifx%5==0][10,20,30]>>>[aforain'abcdefg']['a','b','c','d','e','f','g']>>>cells=[(row,col)forrowinrange(1,10)forcolinrange(1,10)]#可以使用两个循环>>>forcellincells:print(cell)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

字典推导式

字典的推导式生成字典对象,格式如下:
{key_expression : value_expression for 表达式 in 可迭代对象}

类似于列表推导式,字典推导也可以增加if条件判断,多几个for循环。

#统计文本中字符出现的次数>>>my_text='iloveyou,ilovesxt,ilovegaoqi'>>>char_count={c:my_text.count(c)forcinmy_text}>>>char_count{'':9,'i':4,'l':3,'o':5,'v':3,'e':3,'y':1,'u':1,',':2,'s':1,'x':1,'t':1,'g':1,'a':1,'q':1}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

统计字符中单词出现的次数
下面这道题在面试的比试中考过

# 统计字符中单词出现的次数#方法1:推导式my_text='iloveyou,ilovesxt,ilovegaoqi'char_count={c :my_text.count(c) for c in my_text}print(char_count){'think': 1, 'I': 1, 'can': 2, 'because': 1, 'i': 2}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
#方法2:字典def count(str):    count_words = str.split()    count_word = {}    for word in count_words:        if word not in count_word.keys():            count_word[word] = 1        else:            count_word[word] += 1    return count_word    print(count('I can because i think i can')){'I': 1, 'can': 2, 'because': 1, 'i': 2, 'think': 1}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
#方法三 使用collections的Counterfrom collections import Counterstr = 'I can because i think i can'counts = Counter(str.split())print(counts)Counter({'can': 2, 'i': 2, 'I': 1, 'because': 1, 'think': 1})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

集合推导式

集合推导式生成集合,和列表推导式的语法格式类似:
{表达式 for item in 可迭代对象}
或者 {表达式 for item in 可迭代对象 if 条件判断}

>>>{xforxinrange(1,100)ifx%9==0}{99,36,72,9,45,81,18,54,90,27,63}
  • 1
  • 2

生成器推导式(生成元组)

元组有推导式吗,能不能用小括号生成?

>>>(x for x in range(1,100) if x%9==0)<generator object <genexpr> at 0x0000020A0FEF98E0>
  • 1
  • 2

发现提示的是“一个生成器对象。显然,元组没有推导式

一个生成器只能运行一次。第一次迭代可得到数据,第二次迭代发现数据已经没有了。

>>>gnt=(xforxinrange(1,100)ifx%9==0)>>>forxingnt:print(x,end='')918273645546372819099>>>forxingnt:print(x,end='')>>>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
#绘制多个同心圆import turtlet=turtle.Pen()my_colors=('red','green','yellow','black')t.width(4)t.speed(1)for i in range(10):#0 1 2 3 4 t.penup() t.goto(0,-i*10) #0,-100,-200,-300,-400 t.pendown() t.color(my_colors[i%len(my_colors)]) t.circle(15+i*10)#100,200,300,400,,500turtle.done()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

#绘制18*18棋盘#画棋盘import turtlewidth=30num=18x1=[(-400,400),(-400+width*num,400)]y1=[(-400,400),(-400,400-width*num)]t=turtle.Pen()t.speed(10)#t.goto(x1[0][0],x1[0][1])#t.goto(x1[1][0],x1[1][1])for i in range(0,19):    t.penup()    t.goto(x1[0][0],x1[0][1]-30*i)    t.pendown()    t.goto(x1[1][0],x1[1][1]-30*i)for i in range(0,19):    t.penup()    t.goto(y1[0][0]+30*i,y1[0][1])    t.pendown()    t.goto(y1[1][0]+30*i,y1[1][1])t.hideturtle()#隐藏画笔turtle.done()#保证运行窗口不被自动关闭
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
给妹子讲python-S01E04容器遍历和列表解析式
Python 最频繁使用的4个函数:lambda、 map、filter 和 reduce
收获颇多,从5个维度总结python数据结构的关系,发现了这些技巧
Python所有的内置函数 , 都帮你整理好了!
Python学习手册(第4版).4
牛逼!Python的判断、循环和各种表达式(长文系列第2篇)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服