在PHP中使用列表
我需要将一些Python代码重写成PHP(不要恨我,一位客户让我这么做) 在Python中,您可以执行以下操作:在PHP中使用列表,php,python,arrays,Php,Python,Arrays,我需要将一些Python代码重写成PHP(不要恨我,一位客户让我这么做) 在Python中,您可以执行以下操作: // Python numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7] positive = [int(n) for n in numbers if n > 0] negative = [int(n) for n in numbers if n < 0] 而不是像这样做: <?php $numbers =
// Python
numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7]
positive = [int(n) for n in numbers if n > 0]
negative = [int(n) for n in numbers if n < 0]
而不是像这样做:
<?php
$numbers = array(34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7);
$positive = array();
$negative = array();
foreach($numbers as $n) {
if($n > 0):
$positive[] = intval($n);
else:
$negative[] = intval($n);
endif;
}
?>
有没有一种方法可以像在Python中那样用更少的代码来编写它?没有。。。就我所知,foreach循环是唯一的方法 这并不是更多的代码
但是,如果您想让它稍微短一点,可以在foreach循环之前去掉显式数组声明。PHP在数组/映射处理方面有点冗长,这是Python的优势之一。有一些函数可以帮助处理数组,例如:
$positive = array_filter($numbers,function($n){return $n > 0;});
$positive = array_map('intval',$positive);
$negative = array_filter($numbers,function($n){return $n < 0;});
$negative = array_map('intval',$positive);
$positive=array_filter($numbers,function($n){return$n>0;});
$positive=数组映射($intval',$positive);
$negative=array_filter($numbers,function($n){return$n<0;});
$negative=数组映射($intval',$positive);
当然可以。使用
$positive=array_filter($numbers,function($a){return$a>0;});
$negative=array_filter($numbers,function($a){return$a<0;});
您可以使用和匿名函数(只有当您使用PHP5.3或更高版本时,才可以使用后者),但您使用更多代码显示的方式更高效,而且在我看来更整洁
$positive = array_filter($numbers, function($x) { return $x > 0; });
$negative = array_filter($numbers, function($x) { return $x < 0; });
如果不解释为什么被否决,那么否决就不是很有建设性的….-1给人的印象是Python比PHP好,因为我可以用更少的字符在Python中编写东西,除非有人能够证明otherwise@MarkBaker我使用PHP的唯一原因是我们的客户为此付费。我们自己更喜欢Python。@MathieuDumoulin:下次再仔细阅读括号:)人们总是说只有在5.3上才能工作是不必要的。如果有人使用的是旧版本的PHP,他无论如何都是注定要失败的。我正在使用PHP5.4,喜欢它的每一个特性:)去掉显式数组声明会引起警告。PHP5.3不是问题MathieuPHP 5.3于2009年6月30日发布,人们停留在较低版本上,特别是对于像这样的新项目,需要认真重新考虑他们的服务器维护或宿主。是的。。我们的服务器上安装了PHP5.3
$positive = array_filter($numbers,function($a) {return $a > 0;});
$negative = array_filter($numbers,function($a) {return $a < 0;});
$positive = array_filter($numbers, function($x) { return $x > 0; });
$negative = array_filter($numbers, function($x) { return $x < 0; });
$positive = array_map('intval', array_filter($numbers, function($x) { return $x > 0; }));
$negative = array_map('intval', array_filter($numbers, function($x) { return $x < 0; }));