if statement - Python - Applying multiple conditions output in list comprehension -


i have been trying code rgb hex function in python when faced problem wasn't able figure out how do. here function itself:

def rgb(r, g, b):     return ''.join([format("{0:x}".format(x).rjust(2, "0").upper()) if int(x) >= 0 else "00" if int(x) <= 255 else "ff" x in [r,g,b]]) 

the important part: if int(x) >= 0 else "00" if int(x) <= 255 else "ff"

what want able apply different output if number lower 0 or higher 255. first if works, second ignored. how can multiple conditions in list comprehension?

you current ... if ... else ... clause doesn't make sense:

format("{0:x}".format(x).rjust(2, "0").upper()) if int(x) >= 0 else "00" if int(x) <= 255 else "ff" 

means:

  • format(...) if int(x) >= 0
  • else, if int(x) < 0,

    • 00 if int(x) <= 255 (but less 0 must less 255);
    • else ff

presumably meant have:

"ff" if int(x) > 255 else ("00" if int(x) < 0 else format(...)) 

but surely, isn't easier use standard max-min construct?

"{0:02x}".format(max(0, min(int(x), 255))) 

note here 0 padding , upper casing in format specifier (02x)


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -