一、三元表达式
name=input('姓名>>: ')
res='SB' if name == 'alex' else 'NB'
print(res)
二、列表解析
l = []
for i in range(10):
if i >= 5:
l.append('egg%s' % i)
print(l)
####列表解析
l = ['egg%s' % i for i in range(10) if i >= 5]
print(l)
三、生成器表达式
g = ('egg%s' % i for i in range(1000)) ###用在数据量比较大的场景下
print(g)
print(next(g))
print(next(g))
print(next(g))
##############################################
###把a文件里的内容最长的一行打印出来
with open('a.txt', encoding='utf-8') as f:
# res=max((len(line) for line in f)) ###[len(line) for line in f]
res = max(len(line) for line in f)####(len(line) for line in f) ,统计每一行的长度
print(res)
print(max([1, 2, 3, 4, 5, 6]))###求列表中最大值
#####此方法适用大文件
with open('a.txt', encoding='utf-8') as f:
g = (len(line) for line in f)
print(max(g))
四、应用
res = sum(i for i in range(3)) #sum求和
print(res)
'''
1、求总共花了多少钱
db.txt文件内容:
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()##取出每一行按空格做切分
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文件里的商品取出来放到一个列表里去,最终实现[{'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)