day4_python之三元表达式、列表推导式、生成器表达式
2024-10-07 23:57:48
一、三元表达式
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)
最新文章
- 数据库大数据处理---复制(SQLServer)
- LoadRunner Pacing设置(转)
- 参考:(Java Selenium)Element is not visible to clcik
- SQL报错error:索引中丢失IN或OUT參数
- ckplayer,超酷网页播放器,用于集成在网站中的播放器
- jquery中this与$this的区别
- Spring Boot gradle
- linux-ubuntu关闭防火墙
- SQLHELPER 帮助类
- Java面试04|Spring框架
- Python基础-类
- JPA + SpringData 操作数据库原来可以这么简单 ---- 深入了解 JPA - 1
- shell函数-3
- /usr/bin/ld: .build_release/tools/alignment_tools.o: undefined reference to symbol 'omp_get_thread_num@@OMP_1.0'
- uni-app 如何在当前页调上个页面的方法
- const与volatile
- python:3种爬虫的优缺点
- airflow 实战
- 软件开发架构、网络基础知识、osi七层模型
- metasploit framework(五):meterpreter基本命令和python扩展
热门文章
- 使用MySQL会话变量实现窗口函数
- jps的用法及常见问题介绍
- 移动端 Iphone拍照变横问题的解决
- 磁力搜索网站 BT torrent search engine 推荐 2019/12/25日更新
- CesiumLab V1.1 新功能 (免费Cesium处理工具集)
- 学习JDK1.8集合源码之--PriorityQueue
- Docker搭建ELK的javaweb应用日志收集存储分析系统
- hadoop-hive查询ncdc天气数据实例
- 洛谷1081 (NOIp2012) 开车旅行——倍增预处理
- QT_string转char*