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

问题描述

我正试图凝结:

samp_neighs = [_set(_sample(to_neigh,num_sample,)) if len(to_neigh) >= num_sample else to_neigh for to_neigh in 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)
,

如果目标只是提高可读性(因为编写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))