我如何在使用带有 if else 表达式的列表理解创建的表达式中重用相同的列表?在单个语句/表达式中实现它(不使用任何中间变量)
即 index = 0 if [listcomprehension]
为空否则获取列表理解的第一个元素而不重新创建它
carIndex = [index
for index, name in enumerate([car.name for car in cars])
if "VW" in name or "Poodle" in name][0]
最佳答案
如果您不打算存储列表,则使用默认值为 0 的生成器表达式和 next,创建一个毫无意义:
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,所以我不确定这是否是您想要的。这实际上将返回与 cars 中的名称匹配的汽车的索引:
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
关于Python:如何在表达式中创建列表理解后重新使用它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28190922/