shripati007
shripati007

Reputation: 87

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

Is it possible to convert the for loop with an if-condition, in the given code, to a list comprehension?

    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)

I tried using standard definition to compress this for loop into list comprehension but it doesn't seem to work. Would it be possible to convert this for-loop into a list comprehension in the first place? And if yes, what is the best way to do it?

Upvotes: 0

Views: 449

Answers (3)

Eli Stevens
Eli Stevens

Reputation: 1447

No, I don't believe you can express that as a list comprehension (at least, not without making it significantly worse to understand/debug).

The key part is that you're updating Value and ListIndex on some of the iterations, and needing those updated values to persist to future iterations. That's not really how list comprehensions work, since they're meant to replace the map() function. The basic form is:

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

Your output is a list of f(x) return values, and that can't depend on earlier values of x passed in unless f keeps global state (which is gross; don't do that).

Upvotes: 0

mhhabib
mhhabib

Reputation: 3121

Use enumerate to get both index and value. Also, you can set default value using else

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

Upvotes: 1

Kenan
Kenan

Reputation: 14094

I don't think you need ListIndex variable since you can get it from enumerate

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

Upvotes: 1

Related Questions