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.

5
  • 1
    I think everybody is asking themselves "what is maxsize?" Commented Nov 3, 2017 at 21:25
  • I think your syntax error is that you're nesting ternaries without giving the second ternary an else statement. Commented Nov 3, 2017 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. Commented Nov 3, 2017 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? Commented Nov 3, 2017 at 21:36
  • Check out this post for info on max int value - stackoverflow.com/questions/9860588/… Commented Nov 3, 2017 at 21:41

1 Answer 1

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

1 Comment

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

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.