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

问题描述

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

另外一个没有 ifelse 在列表 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)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...