【问题标题】:Indent-Expected errors while trying to write one-line list comprehension: if-else variants尝试编写单行列表理解时出现缩进预期错误:if-else 变体
【发布时间】:2021-05-24 13:49:46
【问题描述】:

我正在尝试在一行中编写一个包含 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中的保留关键字,你想干什么?
  • @KrishnaChaurasia 在综合列表中,当我遍历初始列表的元素时,我需要忽略一些元素,因为我添加了continue if sublist == block
  • 使用0 或负值,因为无论如何您都在使用列表中的max()

标签: python for-loop conditional-statements list-comprehension


【解决方案1】:

continue 是 Python 中的保留关键字,因此您会收到错误消息。

您不需要continue 来跳过元素。

列表comprehension 中还有一个不带elseif

基于 cmets,如果您只需要跳过元素,您可以只使用 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)

【讨论】:

    猜你喜欢
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 2013-06-18
    • 2019-02-23
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 2020-11-15
    相关资源
    最近更新 更多