三元公式
三元表达式是if.else的缩写。
x=1
y=2
res=x if xy else y #三元表达式,True返回左侧的值,False返回右侧的值
是打印(RES )
分析列表
列表分析用于快速生成列表,可以简化代码。
L=[IforIinrange(10 ) ]
打印(l ) )。
L=['book%s'%IforIinrange(10 ) if i5 if i7]
打印(l ) )。
对旧列表进行计算处理,如计算平方:
l=[ 1,2,3,4,5 ]
L2=[ items * *2foritemsinlifitems * * 216 ]
打印(L2 )。
筛选列表中的值:
l=['book1 '、' book2 '、' book3'、' pc '、' iphone']
L2=[ iforiinlifi.starts with (book ) ]
打印(L2 )。
发电机式
生成器表达式主要用于生成以下迭代器:
l=['book1 '、' book2 '、' book3'、' pc '、' iphone']
L2=(iforiinlifi.starts with (book ) )
打印(下一步(L2 ) ) )
打印(下一步(L2 ) ) )
打印(下一步(L2 ) ) )
如果将列表中的大括号[]更改为括号[],则为生成器表达式。 这主要用于处理大文件和无限列表问题。
检查文件内容以找到最长的行长度。
withopen(a.txt ),encoding=) utf-8 ) ) as f:
g=max(len(I ) for i in f ) max函数具有内置的遍历迭代器中值的next方法,如果存在多个括号,则可以省略迭代器括号
是打印(g )
可以直接计算列表和生成器的值。
合计print (sum ([ 1,2,3 ] )列表中的值
打印(sum (iforiinrange )4) #生成器合计
合并文件中的相关数据时:
文件a.txt的内容如下:
a 100 5
b 20 100
c 5000 2
d 10000 3
第2列为单价,第3列为数量时,求出合计金额。
withopen(a.txt ),encoding=) utf-8 ) ) as f:
g=(float ) I.split (([1] int ) I.split ) [2] (for I in f ) ) ) ) ) ) )
打印(sum ) g ) )
同样,可以使用上面的文本内容设置格式并完成过滤操作:
withopen(a.txt ),encoding=) utf-8 ) ) as f:
g={'name':I.split((0)、' price ' : float (I.split ) )1)、' count ' : int (I.split ) ) )
是打印(g )
输出结果:
[{'name': 'c ',' price': 5000.0,' count': 2},{'name': 'd ',' price': 10000.0,' co