首页 > 解决方案 > 将列表元素与捕获进行比较:相互比较必须首先发生......元素顺序也很重要

问题描述

我正在用 Jython/Python 编写一个用于图像分析的脚本(使用 ImageJ)。我的目标是将图像相互比较...

为清楚起见进行编辑:列表中的每个元素都必须与其他元素进行比较,但不允许进行自我比较。)

...但我有一些具体的要求。这些要求基于我使用预定义插件的事实。

例如:

imagefiles = ["A", "B", "C"]

第一:顺序很重要。 "A"vs 与vs"B"不同。"B""A"

第二:列表的大小是可变的,基于用户输入。在此示例中,用户输入了 3 个文件:A,B,C,但代码需要容纳元素数量不等于 3 的实例。

第三:不允许自我比较。即:"A"vs "A". 不能发生。

第四:我希望在进入下一个元素之前进行比较。例如:

"A" vs "B"那时"B" vs "A"而不是"A" vs "B"那时"A" vs "C"

第五:我最终需要以字符串的形式访问元素(由于将用户定义的变量调用到预先存在的插件中而需要)。

为清楚起见,必须进行的比较是:

"A" vs "B"
"B" vs "A"
"A" vs "C"
"C" vs "A"
"B" vs "C"
"C" vs "B"

我能够生成一个代码,除了第四个要求之外的所有事情......首先是相互比较。但我真的坚持如何使比较的顺序成为我想要的。这是当前的工作片段,符合我的第四个要求。

from ij import IJ  #using Jython scripting in the ImageJ program

imagefiles = ["A", "B", "C"]

for index, imgs in enumerate(imagefiles):
    for s, secondimage in enumerate(imagefiles):
        if s != index:
            IJ.run("PluginFE", "element1="+imgs+" element2="+secondimage) #this calls the plugin (PluginFE) within the ImageJ program)

I'm trying to think about how to accomplish the comparison order requirement...and coming up with something like this:

for imgs in imagefiles:
    for index in range(len(imagefiles)):
      if index < len(imagefiles):
        IJ.run("PluginFE", "element1="+imgs+"element2="+imagefiles[index+1])

but this fails with the error

IndexError: index out of range: 3

I understand the error,and the problem...I just can't figure out how to work around. I'm still pretty new to coding, so I may be missing an obvious python function!

Thanks for any input

标签: pythonloopsiterationjythonimagej

解决方案


Try this:

for index, imgs in enumerate(imagefiles[:-1]):
    for secondimage in imagefiles[index+1:]:
        IJ.run("PluginFE", "element1="+imgs+" element2="+secondimage)
        IJ.run("PluginFE", "element1="+secondimage+" element2="+imgs)

Starting the inner loop from the next element after the one in the outer loop ensures that each pair is only processed once, and imgs will always be the earlier one. Then it calls IJ.run() with the images in the two orders, first with imgs vs secondimage, then secondimage vs imgs.

I think you can use itertools.combinations as well:

import itertools
for imgs, secondimage in itertools.combinationa(imagefiles, 2):
    IJ.run("PluginFE", "element1="+imgs+" element2="+secondimage)
    IJ.run("PluginFE", "element1="+secondimage+" element2="+imgs)

推荐阅读