如何将此列表理解扩展为多行 for 循环?

How can I expand this list comprehension into a multi-line for loop?

我正在尝试解压缩:

samp_neighs = [_set(_sample(to_neigh, 
                            num_sample,
                            )) if len(to_neigh) >= num_sample else to_neigh for to_neigh in to_neighs]

分成多行。有人可以帮忙吗?提前致谢!

如果目标只是提高可读性(因为编写 for 循环没有其他好处),您可以将 _set(...) if .. else .. 提取到它自己的函数中,而不是将其推入列表理解中

例如

def foo(to_neigh, num_sample):
    s = _sample(to_neigh, num_sample,)
    return _set(s) if len(to_neigh) >= num_sample else to_neigh

然后您可以将该函数映射到列表上

num_sample = ...
samp_neighs = list(map(lambda n: foo(n, num_sample), to_neighs))

如果我把你的代码写成几行而不是一行,它看起来会像这样:

result = []

for to_neigh in to_neighs:
    if len(to_neigh) >= num_sample:
        result.append(_set(_sample(to_neigh, num_sample)))
    else:
        result.append(to_neigh)