0

I have a string in an input that needs to be split into separate values and left in a list. I am using the following construct to enter values. How can the value -1 be noticed on a variable var?

import sys
readline = sys.stdin.readline
var = 10**5

current_line = list(map(int, readline().split()))

Example input:

-1 3 0 -1 4 5

Required value current_line:

[var, 3, 0, var, 4, 5]
Lib
  • 29
  • 5

3 Answers3

1

Just check for -1s as you go and replace them with var:

current_line = [var if i == -1 else i for i in map(int, readline().split())]

var if i == -1 else i is Python's ternary conditional operator (more precisely "conditional expression"), so -1 values get replaced, and all others are kept unchanged.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
1

You can use a simple list comprehension for that:

x = [-1, 3, 0, -1, 4, 5]

var = 10**5

# loop through all elements and if the element is -1 replace it with var, else keep the old element
x = [var if i == -1 else i for i in x]
koegl
  • 505
  • 2
  • 13
1

Replace -1 with var as you iterate over the list of values.

current_line = [var if x == -1 else x for x in map(int, readline().split())]

I'd probably forgo the use of map altogether in this case. No use converting '-1' to -1 if you're going to immediately discard the int value anyway.

current_line = [var if x == '-1' else int(x) for x in readline().split()]

For a different emphasis, negate the comparison.

current_line = [int(x) if x != '-1' else var for x in readline().split()]
chepner
  • 497,756
  • 71
  • 530
  • 681