使用生成器表达式,然后使用默认值0,如果您不打算存储列表,则创建一个是无意义的:
carIndex = next((index for index, name in enumerate(car.name for car in
cars if "VW" in car.name or "Poodle" in car.name)),-1)
如果匹配,您的原始逻辑将始终返回0,因此我不确定这是否是您想要的.这实际上会返回与汽车名称匹配的汽车索引:
carIndex = next((index for index, car in enumerate(cars)
if any(x in car.name for x in ("VW","Poodles"))), -1)
你的第一个例子相当于:
carIndex = next((0 for _ in (car for car in
cars if "VW" in car.name or "Poodle" in car.name)),-1)
这将简单地成为:
carIndex = 0 if any("VW" in car.name or "Poodle" in car.name for car in cars) else -1