2010-06-24 27 views
6

我有一系列值。他们可以都是平等的或不平等的。所以在XQuery中,我想获得序列中最频繁的项目。使用XQuery获取序列中最重复的元素

let $counter := 0, $index1 := 0 
for $value in $sequence 
if (count(index-of($value, $sequence))) 
then 
{ 
$counter := count(index-of($value, $sequence)) $index1 := index-of($value) 
} else {} 

我不能做这个工作,所以我想我做错了什么。

在此先感谢您提供的任何帮助。

+0

再好问题(+1)。答案是一个XPath单行表达式......将尽量缩短它。 – 2010-06-24 19:17:12

回答

6

使用

for $maxFreq in 
      max(for $val in distinct-values($sequence) 
        return count(index-of($sequence, $val)) 
       ) 
    return 
     distinct-values($sequence)[count(index-of($sequence, .)) eq $maxFreq] 

更新,2015年12月

这是特别短,虽然可能不会太效率高达:

$pSeq[index-of($pSeq,.)[max(for $item in $pSeq return count(index-of($pSeq,$item)))]] 

最短表达可以被构造为3.1的XPath:

enter image description here

甚至更​​短,能够复制 - 使用一个字符名:

$s[index-of($s,.)[max($s ! count(index-of($s, .)))]] 
+0

非常感谢,我认为我的经验不足导致我尝试了一种非常扭曲的方法。 – deb 2010-06-25 07:46:59

1

你正在从一个迫切需要的角度来解决这个问题。

在XQuery中,您可以设置变量的值,但您永远无法更改它们。

做迭代式算法的正确方法是用递归函数:

declare funciton local:most($sequence, $index, $value, $count) 
{ 
    let $current=$sequence[$index] 
    return 
    if (empty($current)) 
    then $value 
    else 
     let $current-count = count(index-of($current, $sequence)) 
     return 
     if ($current-count > $count) 
     then local:most($sequence, $index+1, $current, $current-count) 
     else local:most($sequence, $index+1, $value, $count) 
} 

但接近问题的一个更好的方法是通过描述一个非迭代的方式的问题。在这种情况下,序列中的所有不同值都需要显示任何不同值的最大次数的值。

以前森泰斯翻译成XQuery是

let $max-count := max(for $value1 in distinct-values($sequence) 
         return count(index-of($sequence, $value1))) 
for $value2 in distinct-values($sequence) 
where (count(index-of($sequence, $value2)) = $max-count 
return $value2 
+0

非常感谢你,我已经尝试过你的方式,也有效。 – deb 2010-06-25 07:48:04