0

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?

3 Answers 3

1

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]
Sign up to request clarification or add additional context in comments.

Comments

1

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)]

Comments

0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.