在单行中嵌套for循环

时间:2018-04-26 12:08:28

标签: python

我有逻辑需要计算迭代次数

counts = []
for .. in ..:
    count = 0
    for .. in ..:
        if ..:
            count +=1
    counts.append(count)

如何在python中将此逻辑更改为单行循环

1 个答案:

答案 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)