Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print with inline if statement?

This dictionary corresponds with numbered nodes:

{0: True, 1: True, 2: True, 3: False, 4: False, 5: False, 6: True, 7: True, 8: False, 9: False}

Using two print statements, I want to print marked and unmarked nodes as follows:

  • Marked nodes: 0 1 2 6 7

  • Unmarked nodes: 3 4 5 8 9

I want something close to:

print("Marked nodes: %d" key in markedDict if markedDict[key] = True)
print("Unmarked nodes: %d" key in markedDict if markedDict[key] = False)
like image 673
pooperdooper Avatar asked Feb 05 '16 22:02

pooperdooper


People also ask

How do you inline an if statement in Python?

Syntax of Inline if-else in Python To write an Inline if-else statement we have to follow this syntax. In this syntax, <expression1> will be returned or executed if the condition is true, or else <expression2> will be returned or executed, and these conditions are always executed from left to right.

What is an inline if statement?

It is commonly referred to as the conditional operator, inline if (iif), or ternary if. An expression a ? b : c evaluates to b if the value of a is true, and otherwise to c . One can read it aloud as "if a then b otherwise c".

How do you print an if statement in Python?

Example: Python if Statement # If the number is positive, we print an appropriate message num = 3 if num > 0: print(num, "is a positive number.") print("This is always printed.") num = -1 if num > 0: print(num, "is a positive number.") print("This is also always printed.")

How do I print on the same line with different statements?

To print multiple expressions to the same line, you can end the print statement in Python 2 with a comma ( , ). You can set the end argument to a whitespace character string to print to the same line in Python 3. With Python 3, you do have the added flexibility of changing the end argument to print on the same line.


2 Answers

You can use list comprehensions:

nodes = {0: True, 1: True, 2: True,
         3: False, 4: False, 5: False,
         6: True, 7: True, 8: False, 9: False}

print("Marked nodes: ", *[i for i, value in nodes.items() if value])
print("Unmarked nodes: ", *[i for i, value in nodes.items() if not value])

Output:

Marked nodes:  0 1 2 6 7
Unmarked nodes:  3 4 5 8 9
like image 161
Mohammed Aouf Zouag Avatar answered Sep 24 '22 17:09

Mohammed Aouf Zouag


Here's another solution that works with versions of python which do not support the unpacking syntax used in the top answer yet. Let d be your dictionary:

>>> print('marked nodes: ' + ' '.join(str(x) for x,y in d.items() if y))
marked nodes: 0 1 2 6 7
>>> print('unmarked nodes: ' + ' '.join(str(x) for x,y in d.items() if not y))
unmarked nodes: 3 4 5 8 9
like image 23
timgeb Avatar answered Sep 23 '22 17:09

timgeb