2010-06-24 41 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