Skip to main content
 首页 » 编程设计

Python: [(x, y) for (x, y) in list_of_tuples if f(x) is not empty]

2025年05月04日9myhome

我有以下格式的元组列表:

input_list = [(x1, y1), (x2, y2), ... , (xn, yn)] 

我想通过在每个元组的第一个参数上应用一个函数并将其存储在不同的元组列表中,将这个列表转换为另一个列表。所以:

new_list = [(func(x), y) for (x, y) in input_list] 

问题是,func(x) 可能会返回一个空字符串。在那种情况下,我不希望元组 (func(x), y) 位于 new_list 中。我希望我可以做类似的事情:

new_list = [(func(x), y) for (x, y) in input_list if func(x)] 

但这会导致双倍的计算量并且效率极低。我怎样才能做到这一点?

请您参考如下方法:

您可以只使用常规的for循环:

new_list = [] 
for x, y in input_list: 
    result = func(x) 
    if result: 
        new_list.append((result, y)) 

如果您坚持单行列表理解,您可以使用:

[(res, y) for x, y in input_list for res in (func(x),) if res] 

单元素元组上的嵌套循环为您提供了对函数输出的引用。然而,这将需要另外 3 行注释来向 future 的维护者解释你到底在做什么,因此显式循环(在我看来)是更好的选择。

第三种选择是首先嵌入一个转换输入的生成器表达式:

[(res, y) for res, y in ((func(x), y) for x, y in input_list) if res] 

对于维护者来说,这可能又需要一次认知上的飞跃,这可能不值得。