【问题标题】:How to print with inline if statement?如何使用 inline if 语句打印?
【发布时间】:2016-02-05 22:47:13
【问题描述】:

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

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

【问题讨论】:

    标签: python dynamic printing inline


    【解决方案1】:

    您可以使用列表推导:

    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
    

    【讨论】:

    • 你可以只做 if value 和 if not value
    • 也适用于 Python 3.4.0。
    • 效果很好!谢谢!
    【解决方案2】:

    这是另一个适用于不支持最佳答案中使用的解包语法的 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
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2013-11-05
        • 2021-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-15
        • 2020-09-19
        • 1970-01-01
        • 2019-02-06
        相关资源
        最近更新 更多