首页 > 解决方案 > python中的if-for-else嵌套集合理解

问题描述

我正在尝试将以下嵌套条件转换为设置理解,但无法使其正常工作。

processed = set()
if isinstance(statements, list):
    for action in statements:
        processed.add(action)
else:
    processed.add(statements)

我尝试了以下但看起来我犯了一个错误

processed = {action for action in statements if isinstance(statements, list) else statements}

编辑:哪里statements可以是列表或字符串。

标签: pythonpython-3.xlist-comprehensionset-comprehension

解决方案


您需要if集合理解之外的语句,如本else例所示,statements它不是可迭代的

processed = {action for action in statements} if isinstance(statements, list) else {statements}

推荐阅读