簡體   English   中英

如何使用內聯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}

使用兩個打印語句,我想打印標記和未標記的節點,如下所示:

  • 標記節點: 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)

您可以使用列表推導:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM