One or three meta-expressions
Name=input (' name >>: ') res= ' SB ' If name = ' Alex ' Else ' NB ' Print (res)
Second, list analysis
L = []for i in range]: If I >= 5: l.append (' egg%s '% i) print (L) # # # #列表解析l = [' egg%s '% i for I in range (Ten) I F I >= 5]print (l)
Third, generator expression
g = (' egg%s '% i for I in range) # # #用在数据量比较大的场景下print (g) Print (Next (g)) print (Next (g)) print (next) ########## ###################################### #把a文件里的内容最长的一行打印出来with Open (' a.txt ', encoding= ' utf-8 ') as F: # Res=max (( Len (line), line, F)) ###[len (line) for line on F] res = max (len (line), line, F) # # # # # # # # # # # # # # # # # # (Len Line) n f), count the length of each line print (res) print (max ([1, 2, 3, 4, 5, 6]) # # # #求列表中最大值 # # # # # # # # # # # # # #此方法适用大文件with Open (' a.txt ', encoding= ' utf-8 ') As f: g = (len (line) to line in F) print (max (g))
Iv. Application
res = SUM (i for I in range (3)) #sum求和print (RES)
‘‘‘
1. How much does it cost to pay for the total?
Db.txt File Contents:
Apple 10 3
Tesla 100000 1
MAC 3000 2
Lenovo 30000 3
Chicken 10 3
‘‘‘
# # # #笨拙的方法with Open (' Db.txt ', encoding= ' utf-8 ') as f: l = [] for line in f: goods = Line.split () # #取出每一行按空格做切分 C3/>price = float (goods[1]) # # #取出商品的价钱 count = Int (goods[2]) # # # #取出商品的个数 Cost = Price * count### #价钱乘以个数 L.append (cost) #加入到列表中 print (SUM (l)) # 196060.0### #利用生成器表达式with open (' Db.txt ', encoding= ' utf-8 ') as F: l = (Float (line.split () [1]) * INT (Line.split () [2]) for line in F) print (SUM (l)) # # #把db文件里的商品取出来放到一个列表里去, end implementation [{' Name ': ' Apple ', ' price ': 333, ' Count ': 3},]with open (' Db.txt ', encoding= ' utf-8 ') as f: info = [{' Name ': Line.split () [0], ' price ': float (Line.split () [1]), ' Count ': Int. (Line.split () [2])} for line in F if float (Line.split () [1]) > = 30000] print (info)
Ternary expressions of Day4_python, list derivation, generator expressions