此词典对应于编号节点:
{0: True, 1: True, 2: True, 3: False, 4: False, 5: False, 6: True, 7: True, 8: False, 9: False}
使用两个打印语句,我想打印标记和未标记的节点,如下所示:
标记节点:0 1 2 6 7
未标记的节点:3 4 5 8 9
我想要一些接近的东西:
print("Marked nodes: %d" key in markedDict if markedDict[key] = True)
print("Unmarked nodes: %d" key in markedDict if markedDict[key] = False)
答案 0 :(得分:9)
您可以使用列表推导:
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
答案 1 :(得分:3)
这是另一个适用于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
答案 2 :(得分:0)
我们可以避免在字典上重复迭代。
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))