问题描述
occupied = [8,9,10]
broken = [1,2,3]
output = ['occupied' if x in occupied else x in broken for x in range(1,11)]
desired_output = ['broken','broken',False,'occupied','occupied']
能否一口气实现以上目标?
当前我正在进行两次迭代
['broken' if x2==True else x2 for x2 in ['occupied' if x in occupied else x in broken for x in range(1,11)] ]
我正在寻找这样的东西
['occupied' if x in occupied else 'broken' if x in broken for x in range(1,11)]
但这是不正确的语法
解决方法
您几乎已经拥有了,只需在解决方案中添加一个else
子句(第二个if
表达式):
output = ["broken" if x in broken else 'occupied' if x in occupied else False for x in range(1,11)]
# Out[5]: ['broken','broken',False,'occupied','occupied']
,
如果我理解正确,这应该对您有用
occupied = [8,9,10]
broken = [1,2,3]
["occupied" if x in occupied else "broken" if x in broken else False for x in range(1,11)]
输出:
['broken','occupied']