将嵌套的列表理解转换为常规的for循环

问题描述

我想知道如何使用常规循环编写此列表理解:

sep_class = [[x for x,t in zip(X_train,y_train) if t==c] for c in np.unique(y_train)]

我这样尝试过:

sep_class = []
for c in np.unique(y_train):
    for x,y_train):
        if t == c:
            sep_class.append(x)

但是输出是不同的。我在做什么错了?

解决方法

将列表理解转换为常规循环的最通用方法如下:

l = [f(x) for x in iter]

# converts to:

l = []
for x in iter:
    l.append(f(x))

当您在理解中嵌套列表创建时,这会变得有些复杂,但遵循相同的逻辑,现在f(x)是list-comp本身的翻译。所以我们有:

l = [[g(x) for x in sub] for sub in iter]

# converts to:

l = []
for sub in iter:
    temp = []
    for x in sub:
        temp.append(g(x))
    l.append(temp)

因此,在您的情况下,只需添加条件,list-comp将变为:

sep_class = [[x for x,t in zip(X_train,y_train)if t ==c] for c in np.unique(y_train)]

# converts to:

sep_class = []
for c in np.unique(y_train):
    sub = []
    for x,y_train):
        if t == c:
            sub.append(x)
    sep_class.append(sub)
,
sep_class = []
for c in np.unique(y_train):
    sep_class.append([])
    for x,y_train):
        if t ==c:
            sep_class[c].append(x)

现在它们是相同的。