0

我在php中有一个函数:

function cmp_key($lst){
    $itersect_size = count(array_intersect($zset, $lst)); //zset is a list which i have
    return $intersect_size,-count($lst)
}

然后是python中的这段代码:

list_with_biggest_intersection = max(iterable,key = cmp_key)

鉴于我想使用 php 函数cmp_key作为 max 函数的键,我该如何在 php 中执行上述代码行...

4

2 回答 2

0

调用函数将返回值作为 max 函数的参数传递。

list_with_biggest_intersection = max(iterable, cmp_key($lst));
于 2013-06-16T06:26:44.727 回答
0

在 Python 中复制 @mgilson 的答案,这是 PHP 中的等价物。

function cmp_key($set, $list) {
  return count(array_intersect($set, $list));
}

// This iterates over all lists and compares them with some
// original list, here named $set for consistency with the other example.
$largest = NULL;
foreach ($lists as $list) {
  if (!isset($largest)) {
    $largest = array('list' => $list, 'count' => cmp_key($set, $list));
  }
  else {
    $count = cmp_key($set, $list);
    if ($count > $largest['count']) {
      $largest = array('list' => $list, 'count' => $count);
    }
  }
}
$list_with_biggest_intersection = $largest['list'];
于 2013-06-16T07:54:28.020 回答