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

标签 python dynamic printing inline

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

{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 - 如何使用内联 if 语句打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35234846/

相关文章:

python - Flask 安全性中没有确认链接

python - 使用python从sql中提取数据,进行转换并写回sql表

python - 根据组合框 1 填充组合框 2

c - (Asterisk PBX) 如何从 features.conf 中的 asterisk agi 控制用 C 编写的程序

java - 制作动态序列

c - 在C中显示ppm图像的rgb值和冲突类型错误

python - 在 Python 3.4 中打印变量

python - Django 将字段集图例添加到 ModelForm

linux - Linux 中动态库导出/导入的关键字是什么?

python - 在 IPython 控制台的同一位置打印