Skip to main content
 首页 » 编程设计

python之在使用 For 形成的数组中包含 If

2025年05月04日11lhb25

在 Python 中我有这样的语句:

blog_ids = [c.blog_id for c in connections] 

这基本上告诉 Python 创建连接中所有博客 ID 的数组。不幸的是,如果 connections 对象有一些 None 类型,c.blog_id 将导致异常。有什么语法可以解决这个问题吗?我试过这个但它不起作用:

blog_ids = [c.blog_id for c not None in connections] 

请您参考如下方法:

blog_ids = [c.blog_id for c in connections if c is not None]