2015-04-28 137 views
1

在蟒蛇一个名单,我有两个列表与非唯一值:PHP减去其他

a = [1,2,3,4,5,5,4,3,2,1,2,3,4,5] 

b = [1,2,2,2,5,5] 

要。减去b。从一个 我找到了解决办法:

from collections import Counter as mset 

subtract = mset(a) - mset(b) 

list(subtract.elements()) 

#result is [1, 3, 3, 3, 4, 4, 4, 5]!!!!!!!! 

如何做同样的在PHP中? PHP不支持列表。

和array_diff是没有用的,因为它会删除非唯一值

+0

不知道有一个bult式函数为此,一种方法将过滤数组(请参阅我的答案)。 – Cristik

+0

我回答了你,输出是不同的。也许我需要潜入php收藏并找到解决方案? – user3345632

回答

2

“功能性”的解决方案:

$a = [1,2,3,4,5,5,4,3,2,1,2,3,4,5]; 
$b = [1,2,2,2,5,5]; 
$bCopy = $b; 
$c = array_filter($a, function($item) use(&$bCopy) { 
    $idx = array_search($item, $bCopy); 
    // remove it from $b if found 
    if($idx !== false) unset($bCopy[$idx]); 
    // keep the item if not found 
    return $idx === false; 
}); 
sort($c); 
print_r($c); 

你需要做的$b副本为array_filter回调是破坏性关于数组$b。你也需要对结果进行排序,如果你想得到与python完全相同的输出结果。

+0

输出是不同 ( [2] => 3 [3] => 4 [6] => 4 [7] => 3 [11] => 3 [12] => 4 ) – user3345632

+0

使用解决方案 – Cristik

+0

我认为直觉上可以使用最新的PHP版本或php集合的新特性来解决它。不幸的是,我不是程序员,而是企业家。 – user3345632

1

相关答案:

对于您所提供的例子,你可以尝试以下方法:

$a = [1,2,3,4,5,5,4,3,2,1,2,3,4,5]; 
var_dump($a); 
$b = [1,2,2,2,5,5]; 
var_dump($b); 
$c = array_diff($a, $b); 
var_dump($c); 

它应该给你以下结果:

array (size=14) 
    0 => int 1 
    1 => int 2 
    2 => int 3 
    3 => int 4 
    4 => int 5 
    5 => int 5 
    6 => int 4 
    7 => int 3 
    8 => int 2 
    9 => int 1 
    10 => int 2 
    11 => int 3 
    12 => int 4 
    13 => int 5 
array (size=6) 
    0 => int 1 
    1 => int 2 
    2 => int 2 
    3 => int 2 
    4 => int 5 
    5 => int 5 
array (size=6) 
    2 => int 3 
    3 => int 4 
    6 => int 4 
    7 => int 3 
    11 => int 3 
    12 => int 4 

更新

找到了答案here

我包裹在一个有用的功能的解决方案:

function array_diff_duplicates($array1, $array2) { 
    $counts = array_count_values($array2); 
    $result = array_filter($array1, function($o) use (&$counts) { 
     return empty($counts[$o]) || !$counts[$o]--; 
    }); 
    sort($result, SORT_NUMERIC); 
    return $result; 
} 

尝试以下操作:

$a = [1,2,3,4,5,5,4,3,2,1,2,3,4,5]; 
$b = [1,2,2,2,5,5]; 
$c = array_diff_duplicates($a, $b); 
var_dump($c); 

给人的预期结果:

array (size=8) 
    0 => int 1 
    1 => int 3 
    2 => int 3 
    3 => int 3 
    4 => int 4 
    5 => int 4 
    6 => int 4 
    7 => int 5 
+0

编号输出不同。我需要$ result = arrray(1,3,3,4,4,4,5); – user3345632

+0

谢谢,也是很好的解决方案。 – user3345632