【问题标题】:skipping a turn of a for-loop using except使用 except 跳过 for 循环的一圈
【发布时间】:2018-11-06 11:48:52
【问题描述】:

所以我正在使用通过以下方式向系统添加组件的功能:

es.add(components[i][0] for i in components.keys())

components 是一个 python 字典,看起来像这样:

components = {'a': (a0, a1),
              'b': (b0, None)}

我想要实现的是我想运行上面提到的for-loopexcept,如果components 字典给出None,它将无法运行add() 函数。

我尝试了什么:

es.add(components[i][1] for i in components.keys() except None)

Ofc 它给出了一个语法错误。它的语法是什么?


示例:

es.add(components[i][1] for i in components.keys())

以上等于:

es.add(a1)
es.add(None)

我想以一种只添加 a1 并跳过 None 的方式编写我的 for 循环。

【问题讨论】:

  • 你是什么意思,运行它“期望”?在这种情况下expect 是什么?
  • 如果字典的输入不是None,则运行add()函数。
  • 也许他的意思是除了?
  • 你是对的,固定问题

标签: python dictionary for-loop syntax


【解决方案1】:

我假设它就像[components[i][1] for i in components.keys() if type(components[i][1]) != type(None)]

这样下面的代码就可以正常工作了

es.add(components[i][1] for i in components.keys() if type(components[i][1]) != type(None))

【讨论】:

  • 哦,你是对的,我应该用 if 而不是期望 ^^
  • 不需要type() 的所有东西。 if components[i][1] is not None 会很好。
  • @DanielRoseman 它在我的项目中向我发出警告。我不知道为什么。
  • 这行得通吗? for i in components.keys() if is not None,我想让它尽可能简短。否则我添加components[i][1]
  • @Icedkk 简短回答不,只要脚本应该知道它需要查看数组中的第二个元素:D
【解决方案2】:

使用if 条件,因为except 在这种情况下没有用。您还可以通过直接迭代 dict.values() 使其更短且更具可读性:

es.add(x for _, x in components.values() if x is not None)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多