1

我正在尝试对图像名称列表进行排序。为简单起见,我将其放置在表单的示例 Groovy 列表中:

imageNames=[
'20131018PKH26DRAQ5HOECHST1_A01_T0001F001L01A01Z01C01.tif',
'20131018PKH26DRAQ5HOECHST1_A01_T0001F001L01A01Z01C03.tif',
'20131018PKH26DRAQ5HOECHST1_A01_T0001F001L01A02Z01C04.tif',
'20131018PKH26DRAQ5HOECHST1_A01_T0001F001L01A03Z01C02.tif'
]

我希望能够按照图像名称后缀中存在的任何 T、F、L、A、Z 或 C 代码的数字顺序对该列表进行排序。

因此,例如,如果要根据 C 代码对列表进行排序,则它应按以下顺序显示:

  1. '20131018PKH26DRAQ5HOECHST1_A01_T0001F001L01A01Z01C01.tif',
  2. '20131018PKH26DRAQ5HOECHST1_A01_T0001F001L01A03Z01C02.tif',
  3. '20131018PKH26DRAQ5HOECHST1_A01_T0001F001L01A01Z01C03.tif',
  4. '20131018PKH26DRAQ5HOECHST1_A01_T0001F001L01A02Z01C04.tif'

我曾想过使用比较器使用默认的 Groovy 集合排序方法。但是,我不确定如何将比较器直接写入闭包。我想要类似的东西

imageNames.sort{comparator_for_C}

我可以为每个 T、F、L、A、Z 和 C 代码编写特定的比较器。

4

3 回答 3

3

如果图像文件的名称在 2nd 之前保持不变_,您可以跳过下面的逻辑中的拆分。我想安全一点。

def imageNames=[
'20131018PKH26DRAQ5HOECHST1_A01_T0001F001L01A01Z01C01.tif',
'20131018PKH26DRAQ5HOECHST1_A01_T0001F001L01A01Z01C03.tif',
'20131018PKH26DRAQ5HOECHST1_A01_T0001F001L01A02Z01C04.tif',
'20131018PKH26DRAQ5HOECHST1_A01_T0001F001L01A03Z01C02.tif'
]

def comparator = {str->
    [
      compare: {a,b->
          a.split(/_/)[2].dropWhile{it != str} <=> 
          b.split(/_/)[2].dropWhile{it != str}
      }
    ] as Comparator
}

def comp = ['T', 'F', 'A', 'Z', 'C'].collectEntries{[it, comparator(it)]}

assert imageNames.sort(comp.'C') == [
'20131018PKH26DRAQ5HOECHST1_A01_T0001F001L01A01Z01C01.tif',
'20131018PKH26DRAQ5HOECHST1_A01_T0001F001L01A03Z01C02.tif',
'20131018PKH26DRAQ5HOECHST1_A01_T0001F001L01A01Z01C03.tif',
'20131018PKH26DRAQ5HOECHST1_A01_T0001F001L01A02Z01C04.tif'
]

同样适用于其他字符:

imageNames.sort(comp.'A')
imageNames.sort(comp.'T') ....
于 2013-11-04T21:00:23.380 回答
0

考虑以下:

imageNames.sort { def a, def b ->
    def rank = 0

    def matcherA = (a =~ /.*(...)\.tif/)
    def codeA = matcherA[0][1]
    def matcherB = (b =~ /.*(...)\.tif/)
    def codeB = matcherB[0][1]

    // add your own comparison logic here as desired:        
    rank = codeA.compareTo(codeB)

    rank
}
于 2013-11-04T20:36:38.243 回答
0

只需单独制作比较器,这样就可以了-

   def comparator_for_c = { }
   def sortedList = imageNames.sort(comparator_for_c)

或者是这样的:

def comparators = [c:{}, t:{}, ...]
def sortedListForC = imageNames.sort(comparators.c)

作为示例代码:

def imageNames = ['20131018PKH26DRAQ5HOECHST1_A01_T0001F001L01A01Z01C01.tif',
'20131018PKH26DRAQ5HOECHST1_A01_T0001F001L01A01Z01C03.tif',
'20131018PKH26DRAQ5HOECHST1_A01_T0001F001L01A02Z01C04.tif',
'20131018PKH26DRAQ5HOECHST1_A01_T0001F001L01A03Z01C02.tif']

def sorters = [sort_c:{a, b -> b <=> a }, sort_t:{}]

println "DefaultSort ${imageNames.sort()}"

println "c sort: ${imageNames.sort(sorters.sort_c)}"

只需将您的自定义比较器放在排序器映射中并调用您想要的比较器。

于 2013-11-04T20:33:14.137 回答