【问题标题】:Add item to python dictionary if the bool(item) is True如果 bool(item) 为 True,则将项目添加到 python 字典
【发布时间】:2014-08-28 05:45:15
【问题描述】:

只有当 bool(item) 计算结果为 True 时,我才想将项目添加到字典中:

if item_to_add:
    d["name_of_item"] = item_to_add

有没有办法在 1 行中做到这一点? 谢谢。

【问题讨论】:

  • 你为什么要在意一行行呢?
  • 我必须多次重复上面的行,我想知道是否有办法缩短代码(或行数)
  • 如果你有很多这样的行,你应该考虑如何将它们放在一个循环中,而不是缩小每个复制粘贴行的代码。

标签: python python-2.7 python-3.x dictionary


【解决方案1】:

是的,有:

if item_to_add: d["name_of_item"] = item_to_add

【讨论】:

  • 哇从来不知道这样的语法谢谢! (将在 15 分钟内标记为答案)
猜你喜欢
  • 2014-07-17
  • 1970-01-01
  • 1970-01-01
  • 2021-07-02
  • 2012-09-20
  • 2018-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多