我有逻辑需要计算迭代次数
counts = []
for .. in ..:
count = 0
for .. in ..:
if ..:
count +=1
counts.append(count)
如何在python中将此逻辑更改为单行循环
答案 0 :(得分:3)
将sum()
与嵌套列表推导使用:
counts = [sum([1 for c in b if p(c)]) for b in a]
这相当于:
counts = []
for b in a:
count = 0
for c in b:
if p(c):
count = count + 1
counts.append(count)