0

I'm trying to send a command through a port to another program. In the second program I want to see if a light exists, and if so, set up a new variable which is equal to that light. Over three lines of code it looks like this...

for light in mari.lights.list(): 
    if light.isEnvironmentLight():      
        myEnvLight = light  

Then, I'll be able to set some attributes for 'myEnvLight' over some additional socket commands... The trouble I'm having is in sending a for and if statement through as a single line command.

I've tried using 'list comprehension' to cut down the 'for' part of the code, and then I'm trying to use a ternary operator to simplify the 'if' part. Both of these things are new to me. The result I have so far is

myEnvLight = [light if light.isEnvironmentLight() else 0 for light in mari.lights.list()]

Now this probably strikes most of you as a bunch of nonsense, but it's the best I've got so far! So, just wondering if anyone has a way of fitting those three lines down to one line?

vaultah
  • 44,105
  • 12
  • 114
  • 143
  • if it's just the first match http://stackoverflow.com/questions/9868653/find-first-list-item-that-matches-criteria – dm03514 Aug 13 '15 at 17:30
  • your line is actually quite close. you can move the if after the for, to benefit from the `for if` comprehension form of python, and use `next` to get the first element of the list (which can also be a generator, for simplicity). – njzk2 Aug 13 '15 at 17:34
  • thanks njzk2 I got it with the line: myEnvLight=next(x for x in mari.lights.list() if x.isEnvironmentLight()) – user2407089 Aug 13 '15 at 18:11

0 Answers0