一、三元表达式

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)

最新文章

  1. 数据库大数据处理---复制(SQLServer)
  2. LoadRunner Pacing设置(转)
  3. 参考:(Java Selenium)Element is not visible to clcik
  4. SQL报错error:索引中丢失IN或OUT參数
  5. ckplayer,超酷网页播放器,用于集成在网站中的播放器
  6. jquery中this与$this的区别
  7. Spring Boot gradle
  8. linux-ubuntu关闭防火墙
  9. SQLHELPER 帮助类
  10. Java面试04|Spring框架
  11. Python基础-类
  12. JPA + SpringData 操作数据库原来可以这么简单 ---- 深入了解 JPA - 1
  13. shell函数-3
  14. /usr/bin/ld: .build_release/tools/alignment_tools.o: undefined reference to symbol 'omp_get_thread_num@@OMP_1.0'
  15. uni-app 如何在当前页调上个页面的方法
  16. const与volatile
  17. python:3种爬虫的优缺点
  18. airflow 实战
  19. 软件开发架构、网络基础知识、osi七层模型
  20. metasploit framework(五):meterpreter基本命令和python扩展

热门文章

  1. 使用MySQL会话变量实现窗口函数
  2. jps的用法及常见问题介绍
  3. 移动端 Iphone拍照变横问题的解决
  4. 磁力搜索网站 BT torrent search engine 推荐 2019/12/25日更新
  5. CesiumLab V1.1 新功能 (免费Cesium处理工具集)
  6. 学习JDK1.8集合源码之--PriorityQueue
  7. Docker搭建ELK的javaweb应用日志收集存储分析系统
  8. hadoop-hive查询ncdc天气数据实例
  9. 洛谷1081 (NOIp2012) 开车旅行——倍增预处理
  10. QT_string转char*