相关疑难解决方法(0)

如何在Python 3中使用filter,map和reduce

filter,map并且reduce在Python 2中完美地工作.这是一个例子:

>>> def f(x):
        return x % 2 != 0 and x % 3 != 0
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]

>>> def cube(x):
        return x*x*x
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

>>> def add(x,y):
        return x+y
>>> reduce(add, range(1, 11))
55
Run Code Online (Sandbox Code Playgroud)

但是在Python 3中,我收到以下输出:

>>> filter(f, range(2, 25))
<filter object at 0x0000000002C14908>

>>> map(cube, range(1, 11))
<map object at 0x0000000002C82B70> …
Run Code Online (Sandbox Code Playgroud)

python reduce functional-programming filter python-3.x

292
推荐指数
5
解决办法
25万
查看次数

有一种优雅的方法可以将结构简化为简单的数组吗?

这是一个典型的数组结构:

$s = array ('etc'=>'etc', 'fields' => 
  array (
   0 => array (
     'name'=>'year', 'description'=>'Year of ...', 'type'=>'integer',
   ),
   1 =>  array (
     'name'=>'label', 'description'=>'Offical short name', type'=>'string',
   ),
   2 => array (
     'name' => 'xx', 'description' => 'Xx ...', 'type' => 'string',
   )
 ));
Run Code Online (Sandbox Code Playgroud)

这是一种非优雅的方式(或"不那么优雅的方式"),将大数组减少为只包含一列的简单数组:

 $fields = array();
 foreach ($strut['resources'][0]['schema']['fields'] as $r)
    $fields[] = $r['name'];
Run Code Online (Sandbox Code Playgroud)

这有效,但是只用一条指令就可以做同样的事吗?也许使用喜欢array_reduce(),但我不明白如何.


这是其他典型的"优雅PHP问题":

 $fieldsByName = array();
 foreach ($strut['resources'][0]['schema']['fields'] as $r)
    $fields[$r['name']] = array(
        'description' =>$r['description'],
        'type' =>$r['type']
    );
Run Code Online (Sandbox Code Playgroud)

有替代品吗?这里的想法是使用关键字(name …

php data-structures

8
推荐指数
1
解决办法
593
查看次数

PHP:寻找类似Java Stream API的东西

有没有一种办法的数组转换对象字符串数组使用PHP一些自定义的映射。喜欢:

$objs = array(o1, o2, o3);

...

$strings = conv($objs, function($o) -> $o->fieldXYZ);
Run Code Online (Sandbox Code Playgroud)

代替:

$objs = array(o1, o2, o3);

...

$strings = array();

foreach($objs as $obj) {
    $strings []= $obj->fieldXYZ;
}
Run Code Online (Sandbox Code Playgroud)

php lambda map-function

5
推荐指数
1
解决办法
1184
查看次数