首页 > 解决方案 > 我怎么能说在一行中检查“如果 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:一行呢?

标签: pythonlistcomparison

解决方案


你的意思是这个?:

...
if not a_list or a_list[0].property == something:
    ...

推荐阅读