列表解析:[expr for iter_var in iterable if cond_expr]
生成器表达式:(expr for iter_var in iterable if cond_expr)
J = 'aadsjnk'
S = 'asadasbxjscj'
def number(self,J,S):
setJ = set(J)
return sum(s in setJ for s in S)
print(number(0,J,S))
>>>9
- 交叉配对样例
rows = [1,2,3,7]
def cols():
yield 56
yield 2
yield 1
x_product_pairs = ((i,j) for i in rows for j in cols())
for pair in x_product_pairs:
print(pair)
输出:
- 重构样例
寻找文件最长的行,(核心代码)
f = open('/etc/python_code','r')
longest = max(len(x.strip()) for x in f)
f.close()
return longest
Reference:
yield:https://www.jianshu.com/p/d09778f4e055
set(): http://www.runoob.com/python/python-func-set.html
sum(): http://www.runoob.com/python/python-func-sum.html