StarLlama
StarLlama

Reputation: 390

Python - Using List Comprehension to duplicate an array and replace elements

I have a list:distance = [0,6,6,maxsize]

How can I use list comprehension to create a new list with every maxsize element replaced with a -1 and with every 0 removed?

I want the result as this:

distance1 = [6,6,-1]

I have tried this so far but it's a syntax error:

distance1=[-1 if v == maxsize else v if v != 0 for v in distance]

Thanks in advance!

Edit: maxsize is the largest positive integer supported In pythons regular integer type.

Upvotes: 1

Views: 340

Answers (1)

Jack Homan
Jack Homan

Reputation: 413

Is maxsize a variable, the length of the array or a string?

distance1 = [-1 if v == maxsize else v for v in filter(lambda x: x, distance)]

Upvotes: 3

Related Questions