0

I am trying to solve a few problems using Python for arrays. However the input is being provided by the judge in the form of a list.
Sample Input:
[0,2,1,-3]

Now if the list was given as
0 2 1 -3
,it would have been easy to read the input and parse it to a list but I am not able to handle the symbols present in the input. Is there a way to parse this list input to an actual list using Python?

4
  • Is the list that is provided a json compatible list? Commented Jul 20, 2020 at 10:21
  • you could do something like [int(i) for i in input()[1:-1].split()] or if it is json compatible just use json.loads Commented Jul 20, 2020 at 10:24
  • I recommend to show a working example code. Your Information "Now if the list was given as 0 2 1 -3" is very unspecific which data type is used. If they are strings the awnser is correct. But @user13915628 asumed that they are strings. Commented Jul 20, 2020 at 10:27
  • what are you actually trying to achieve here..Do you need to get a list out of the input where the input is a type of list or string or anyothers ? Commented Jul 20, 2020 at 10:30

5 Answers 5

1

You can do something like this if you want to read this [0,2,1,-3] input:

s = input() #[0,2,1,-3]
lst = s[1:-1].split(',')
print(lst)

Output:

['0', '2', '1', '-3']

You can do this to convert the elements to integers:

lst = [int(i) for i in lst]
print(lst)

Output:

[0, 2, 1, -3]
Sign up to request clarification or add additional context in comments.

Comments

1

if the input is a string and in the format of a dictionary or a list (mainly json compatible) then you could try the built-in JSON package.

import json

inp = "[0,2,1,-3]"

data = json.loads(inp)

here inp is of type string and data will be a list. The structure of data can change according to the input provided.

Note: this wont work if the input is like 0 2 1 -3

Comments

0

Use split. Here is a script that may help you.

a = "0 2 1 -3"
b = a.split(" ")
print(b)

The result is:

['0', '2', '1', '-3']

1 Comment

the question specifically states that is not how the input is given
0

If you are passing input through cli like this

python3 script.py 0 2 1 -3

then,

from sys import argv
inputs = argv[1:]
print(inputs)

Comments

0

If you trust the input you can do it like this:

>>> "[0, 2, 1, -3]".strip("[]").split(",")
['0', ' 2', ' 1', ' -3']

If the parsed list should hold integers instead of strings then:

>>> list(map(int, "[0, 2, 1, -3]".strip("[]").split(",")))
[0, 2, 1, -3]

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.