Nuke Python list of objects order based on other list
<p>I got two lists. First one looks like this:</p>

<pre><code>passOrder = [
                    'direct_diffuse',
                    'direct_specular',
                    'direct_specular_2',
                    'indirect_diffuse',
                    'indirect_specular',
                    'indirect_specular_2',
                    'refraction',
                    'reflection',
                    'emission',
                    'sss'
                ]
</code></pre>

<p>and the other one is a list of objects - in this case Nuke nodes:</p>

<pre><code>nodes = nuke.selectedNodes()
</code></pre>

<p>I'm trying to compare each node's name parameter with passOrder list and arrange them in the order given in passOrder. I tried to explicitly set up orderedNodes index but I guess it's not possible when the list is empty at start.</p>

<pre><code>orderedNodes = []
for n in nodes:
    for index, p in enumerate(passOrder):
        if n['name'].value() == p:
            orderedNodes.insert(index, n)
</code></pre>

<p>I've also tried to zip both lists, and sort them - no luck here. Basically I have no idea how to iterate over <code>n['name'].value()</code> component when sorting.</p>

<p>I don't know what your class/function definitions look like, so I'm using these stubs to illustrate my solution:</p>

<pre><code>class Thing:
    def __init__(self, value):
        self.val = value
    def value(self):
        return self.val

class Nuke:
    def __init__(self, name):
        self.n = {"name": Thing(name)}
    def __repr__(self):
        return "Node({})".format(repr(self.n["name".value()))

def selectedNodes():
    return [Nuke("refraction"), Nuke("direct_diffuse"), Nuke("emission")]
</code></pre>

<p>You could sort <code>nodes</code>, using <code>passOrder.index</code> for its key parameter:</p>

<pre><code>passOrder = [
                    'direct_diffuse',
                    'direct_specular',
                    'direct_specular_2',
                    'indirect_diffuse',
                    'indirect_specular',
                    'indirect_specular_2',
                    'refraction',
                    'reflection',
                    'emission',
                    'sss'
                ]

nodes = selectedNodes()
nodes.sort(key=lambda item: passOrder.index(item.n["name"].value()))
print nodes
</code></pre>

<p>Result:</p>

<pre><code>[Node('direct_diffuse'), Node('refraction'), Node('emission')]
</code></pre>

python list sorting object nuke