如何使用内联 if 语句打印?

How to print with inline if statement?

这个字典对应编号的节点:

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

使用两个打印语句,我想打印标记和未标记的节点如下:

我想要接近于:

的东西
print("Marked nodes: %d" key in markedDict if markedDict[key] = True)
print("Unmarked nodes: %d" key in markedDict if markedDict[key] = False)

您可以使用列表理解:

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])

输出:

Marked nodes:  0 1 2 6 7
Unmarked nodes:  3 4 5 8 9

这是另一个适用于 python 版本的解决方案,该版本尚不支持最佳答案中使用的解包语法。让 d 成为你的字典:

>>> 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

我们可以避免对字典进行重复迭代。

marked = []
unmarked = []
mappend = marked.append
unmappend = unmarked.append
[mappend(str(x))if y else unmappend(str(x)) for x, y in d.iteritems()]
print "Marked - %s\r\nUnmarked - %s" %(' '. join(marked), ' '. join(unmarked))