列表生成器
- xxx
- 三元表达式
- name="alex"
- res="SB" if name == "alex" else "shuai"
- print(res)
- -------------
- SB
- 列表生成式
- 语法
- [expression for item1 in iterable1 if condition1
- for item2 in iterable1 if condition2
- for item3 in iterable1 if condition3
- ...
- for item1 in iterable1 if conditionN
- ]
- 事例一
- egg_list=[]
- for i in range(100):
- egg_list.append("egg%s"%(i))
- print(egg_list)
- #上面简写
- li = ["egg%s" %(i) for i in range(100)]
- print(li)
- #加条件
- li = ["egg%s" %(i) for i in range(100) if i>50]
- print(li)
- 事例二
- li = [1,2,3,4]
- s = "hello"
- obj = []
- for num in li:
- for str in s:
- xx = (num,str)
- obj.append(xx)
- print(obj)
- #上面简写
- obj = [(num,str) for num in li for str in s]
- print(obj)
- #只把大于2的和底下拼接
- obj = [(num,str) for num in li if num > 2 for str in s]
- print(obj)
- 列表生成器
- 优点
- 省内存 一次只产生一个值在内存里
- 应用
- 读取一个大文件的所有内容,并且处理行
- f = open("a.txt")
- #方式一:
- li = []
- for line in f:
- line=line.strip()
- li.append(line)
- print(li)
- #方式二: 列表生成式,还占内存
- li=[line.strip() for line in f]
- print(li)
- #方式三: 转化为列表生成器
- li=(line.strip() for line in f)
- print(li)
- #<generator object <genexpr> at 0x10217aa98>
- print(list(li))
- #['123', '123', '567', 'fgg', 'fghhhhh', 'gdgdagfd', 'dggdcbbb']
- sum/for/list
- sum/for/list 都是把可迭代对象变成迭代器,然后next取值,并且捕捉异常
- 事例一
- #列表是可迭代的, sum和 for/list 相同,把里面的参数变成一个迭代器,然后next取值
- print(sum([1,2,3,4]))
- num=(i for i in range(3))
- print(sum(num))
- 事例二
- #事例 计算商品的价格,后两列相乘
- #---- 文件a.txt
- apple 10 3
- tesla 1000 1
- mac 3000 2
- lenovo 200 3
- chicken 10 3
- money_l=[]
- with open("a.txt") as f:
- for line in f:
- goods=line.split() #每一行变成列表,按空格分开
- res=float(goods[-1])*float(goods[-2])
- money_l.append(res)
- print(money_l)
- # [30.0, 1000.0, 6000.0, 600.0, 30.0]
- print(sum(money_l))
- # 7660.0
- #简写
- with open("a.txt") as f:
- g=(float(line.split()[-1])*float(line.split()[-2]) for line in f)
- print(sum(g))