python - 我怎么能说在一行中检查“如果 a_list 为空或 a_list[0].property == something”?
问题描述
考虑
teams = [[], []]
我想将人员添加到团队中,但前提是(1)他们与团队中的其他人在同一家公司,或者(b)如果团队目前是空的。直接的方法是:
for team in teams:
if len(team) > 0: # could also use "if bool(team):"
if team[0].company == new_person.company:
team.append(new_person)
break
else:
continue
else:
team.append(new_person)
break
else:
teams.append([])
teams[-1].append(new_person)
对我来说,做出一个简单的决定似乎有很多行。复杂的因素是空列表的可能性,如果我尝试查看其中一个元素的属性,这会给我一个错误。
我怎么能说if a_list is empty or a_list[0].property == something:
一行呢?
解决方案
你的意思是这个?:
...
if not a_list or a_list[0].property == something:
...
推荐阅读
- laravel - 我创建了新的 laravel 项目,但出现此错误
- php - 将 mcrypt 3DES ECB 转换为 opensle_encrpt
- node.js - AWS Lambda nodejs 上传文件到 ftp
- c++ - 如何在 Freeswitch 模块中链接外部 .cpp 或 .c 文件?在自动生成的 Makefile 中需要进行哪些更改?
- google-cloud-platform - 全新 Spinnaker 安装,无法创建它一直在加载的项目/应用程序
- javascript - 生成特定范围内的加密随机数
- python - 正则表达式函数用于带有逗号和文本的句子,甚至可能延伸到一行
- python-3.x - AttributeError:“_io.BufferedWriter”对象没有属性“startswith”
- python - 如何使用下拉菜单并根据下拉菜单提供更多详细信息
- vbscript - UFT中SwfTable列标题右键操作