问题描述
我正在尝试在一行中编写一个包含 if-else 语句的列表。我已按照此说明进行操作 solution,但我收到了多个 "indent-Expected" 错误。
这是我的代码:
initial= [[1,2,3],[],[]]
for block in initial:
'''
If block is empty move to the next block
'''
if not block: # empty?
continue # change the block
elif block: # full?
packet = block[0]
# True if there is an empty sublist
x = [True for i in initial if len(i) == 0]
# Enter if there is no empty sublist
if not any(x):
# Here is the issue
if packet > max([continue if sublist == block else sublist[-1] for sublist in initial]):
continue
block.remove(packet)
break # New-one
这一行的问题:
if packet > max([continue if sublist == block else sublist[-1] for sublist in initial]):
解决方法
continue
是 Python 中的保留关键字,因此您会收到错误消息。
您不需要 continue
来跳过元素。
另外一个没有 if
的 else
在列表 comprehension
中是完整的。
根据评论,如果您只需要跳过元素,您可以只使用 if
而没有 else
。
这是一个虚拟示例来展示您的需求:
initial = [[1,2],[2,3],[4,5]]
block = [1,2]
res = max([sublist[-1] for sublist in initial if sublist != block]) # just if is enough without else
print(res)