1

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.

StarLlama
  • 380
  • 2
  • 12
  • 1
    I think everybody is asking themselves "what is maxsize?" – developer_hatch Nov 03 '17 at 21:25
  • I think your syntax error is that you're nesting ternaries without giving the second ternary an else statement. – Jack Homan Nov 03 '17 at 21:29
  • maxsize is the largest positive integer supported In pythons regular integer type. I'm sorry I should have specified this in the original post. – StarLlama Nov 03 '17 at 21:31
  • If I do something like this and add another else statement: asdf=[-1 if v == maxsize else v if v != 0 else v for v in distance], it doesn't get rid of the zeroes. Any idea how I can add the second else statement and also get rid of the zeroes? – StarLlama Nov 03 '17 at 21:36
  • Check out this post for info on max int value - https://stackoverflow.com/questions/9860588/maximum-value-for-long-integer – Jack Homan Nov 03 '17 at 21:41

1 Answers1

3

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)]
Jack Homan
  • 383
  • 1
  • 6
  • I'm sorry, I should have specified this. Maxsize is the largest integer supported by Pythons integer type. You can import it: from sys import maxsize – StarLlama Nov 03 '17 at 21:29