PHP从其他列表中减去一个列表

时间:2015-04-28 06:41:51

标签: 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]!!!!!!!!

如何在PHP中执行相同的操作? PHP不支持列表。

array_diff没用,因为它会删除非唯一值

2 个答案:

答案 0 :(得分:2)

“功能性”解决方案:

var fileName = @"d:\1.xlsx"; 
var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=Excel 12.0;";

您需要制作$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具有破坏性。如果你想要与python中的输出完全相同,你还需要对结果进行排序。

答案 1 :(得分: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