如何解决在列表理解的else块中分配值
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']
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。