在 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]!!!!!!!!
如何在 PHP 中执行相同的操作? PHP 不支持列表。
array_diff 没有用,因为它会删除非唯一值
最佳答案
“功能性”解决方案:
$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 中完全相同的输出,则需要对结果进行排序。
关于PHP 从一个列表中减去另一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29912093/