PHP从一个列表中减去另一个列表
在python中,我有两个具有非唯一值的列表:PHP从一个列表中减去另一个列表,php,python,Php,Python,在python中,我有两个具有非唯一值的列表: a = [1,2,3,4,5,5,4,3,2,1,2,3,4,5] b = [1,2,2,2,5,5] 从a中减去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]!!!!!!!! $a = [1,2,3,
a = [1,2,3,4,5,5,4,3,2,1,2,3,4,5]
b = [1,2,2,2,5,5]
从a中减去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]!!!!!!!!
$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);
如何在PHP中实现同样的功能?PHP不支持列表
数组\u diff没有用处,因为它删除了非唯一值一个“功能性”解决方案:
from collections import Counter as mset
subtract = mset(a) - mset(b)
list(subtract.elements())
#result is [1, 3, 3, 3, 4, 4, 4, 5]!!!!!!!!
$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
,因为数组过滤器
回调对数组$b
具有破坏性。此外,如果希望获得与python中完全相同的输出,则需要对结果进行排序。相关答案:
$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);
$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=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
更新
找到了答案
我将解决方案包装在一个有用的函数中:
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];
var_dump($a);
$b = [1,2,2,2,5,5];
var_dump($b);
$c = array_diff($a, $b);
var_dump($c);
$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
不确定函数中是否有bult,一种方法是过滤数组(参见我的答案)。我回答你,输出是不同的。也许我需要深入研究php集合并在那里找到解决方案?输出是不同的([2]=>3[3]=>4[6]=>4[7]=>3[11]=>3[12]=>4)我直觉上认为可以通过上一个php版本或php集合的新功能来解决。不幸的是,我不是程序员,而是企业家。谢谢你的回答。它帮助我解决了我的问题。它帮助我根据员工进出的情况重新生成员工名单。输出是不同的。我需要$result=arrray(1,3,3,4,4,5);