l=[i**2 for i in range(5)]
print(l)
-----------------------------
[0, 1, 4, 9, 16]
‘‘‘
1.for的左边,只要是一个有返回值的就行,可以是变量,可以是函数len(i),也可以是常数
2.在for条件后,还可以跟if条件
‘‘‘
names=[‘lqz_sb‘,‘yj_sb‘,‘jason_sb‘,‘egon‘]
l=[name for name in names if name.endswith(‘sb‘)]
print(l)
---------------------------------------
[‘lqz_sb‘, ‘yj_sb‘, ‘jason_sb‘]
res={i for i in range(5)}
print(res,type(res))
--------------------------------
{0, 1, 2, 3, 4} <class ‘set‘>
dict1 = {f‘k{i}‘:i for i in range(5)}
print(dict1,type(dict1))
-------------------------------------------
{‘k0‘: 0, ‘k1‘: 1, ‘k2‘: 2, ‘k3‘: 3, ‘k4‘: 4} <class ‘dict‘>
对于简单的一些生成器,可直接这样生成
res=(i for i in range(5))
print(res,type(res))
----------------------------------
<generator object <genexpr> at 0x000001E0C777C970> <class ‘generator‘>
print(next(res))
print(next(res))
print(next(res))
print(next(res))
print(next(res))
print(next(res))
------------------------
0
1
2
3
4
简单的应用用途:
计算1-1000000的和
nums=(i for i in range(1000000))
res=sum(nums)
print(res)
----------------------
499999500000
计算一个文档中的字符个数
with open(‘01 迭代器.py‘, mode=‘rt‘, encoding=‘utf-8‘) as f:
data=f.read()
print(len(data)) # 2202
res=0
for line in f:
res+=len(line)
res = sum((len(line) for line in f))
res = sum(len(line) for line in f)
print(res)
原文:https://www.cnblogs.com/chiyun/p/14066034.html