Python學習(七):生成器表示式(expr for iner_var in iterable if cond_expr)
阿新 • • 發佈:2018-11-11
列表解析:[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