Skip to main content
 首页 » 编程设计

python之如何将函数应用于元素集合

2025年05月04日21del

假设我有一个元素数组,我想从中创建一个新的“可迭代对象”,它在每个 next 上应用自定义“转换”。在 python 2.x 下执行此操作的正确方法是什么?

对于熟悉 Java 的人来说,相当于来自谷歌集合框架的 Iterables#transform。

好的,至于一个虚拟示例(来自 Java)

Iterable<Foo> foos = Iterables.transform(strings, new Function<String, Foo>() 
    { 
        public Foo apply(String string) { 
        return new Foo(string); 
        } 
    }); 
 
 
//use foos below 

请您参考如下方法:

生成器表达式:

(foobar(x) for x in S)