尝试编写单行列表理解时出现缩进预期错误:if-else 变体

Indent-Expected errors while trying to write one-line list comprehension: if-else variants

我正在尝试在一行中编写一个包含 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 来跳过元素。

此外,没有 elseif 在列表 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)