将带有 if 条件的 for 循环转换为列表理解

Conversion of for-loop with an if-condition into list comprehension

是否可以将给定代码中带有 if 条件的 for 循环转换为列表理解?

    ListIndex = 0
    timeSeries = []
    Value = defaultValue
    dfLength = len(dfCont.index)

    for i in range(dfLength):
        if abs(dfCont.iloc[i, 0] - occurance[ListIndex]) < 0.0001:
            Value = discreteValues[ListIndex]
            ListIndex = ListIndex + 1
        timeSeries.append(Value)

我尝试使用标准定义将此 for 循环压缩为列表理解,但它似乎不起作用。是否有可能首先将此 for 循环转换为列表理解?如果是,最好的方法是什么?

我认为您不需要 ListIndex 变量,因为您可以从 enumerate

获取它
timeSeries = [discreteValues[idx] for idx, i in enumerate(dfLength) if abs(dfCont.iloc[i, 0] - occurance[ListIndex]) < 0.0001]

使用enumerate 获取索引和值。此外,您可以使用 else

设置默认值
[discreteValues[ListIndex] if abs(dfCont.iloc[i, 0] - occurance[ListIndex]) < 0.0001 else defaultValue for ListIndex, i in enumerate(dfLength)]

不,我不相信你可以将其表达为列表理解(至少,在不使 understand/debug 变得更糟的情况下)。

关键部分是您要在某些迭代中更新 ValueListIndex,并且需要这些更新的值保留到未来的迭代中。这并不是列表理解的真正工作方式,因为它们旨在取代 map() 函数。基本形式为:

[f(x) for x in y if g(x)]

您的输出是 f(x) return 值的列表,并且不能依赖于传入的 x 的早期值,除非 f 保持全局状态(这很恶心;不要那样做)。