user13486304
user13486304

Reputation: 29

Array Splitting in Python With Specific Input

If you are given two arrays as an input in the same line such as

[4,2,1,5,7],[4,1,2,3,5,7,1,2,7]

Is it possible to create separate arrays out of the above input?

arr1 = [4,2,1,5,7]
arr2 = [4,1,2,3,5,7,1,2,7]

I tried to use split(',') but since they are used in the actual arrays this does not work.

The length of the arrays can vary and the example above is just a sample.

Any help would be appreciated!

Upvotes: 1

Views: 52

Answers (3)

alani
alani

Reputation: 13059

What you have there, once converted from a string using eval, is a 2-element tuple containing two lists. (The outer round parentheses are not mandatory in this situation.)

You could unpack it into two variables as follows:

str = '[4,2,1,5,7],[4,1,2,3,5,7,1,2,7]'

arr1, arr2 = eval(str)

Note: if the input string could derive from third-party input (for example in a server application) then eval should not be used for security reasons because it can allow for execution of arbitrary code, and ast.literal_eval should be used instead. (See separate answer by DYZ.) This will also return a 2-tuple of lists in the case of the input shown above, so the unpacking using var1, var2 = ... is unaffected.

Upvotes: 1

Mark
Mark

Reputation: 92440

This isn't the easy way, but if the goal is to learn to manipulate strings and lists, you can actually parse this the hard way as a stream of characters.

a = "[4,2,1,5,7],[45,1,2,3,5,7,100,2,7]"

l = []

current_n = ''
current_l = None

for c in a:
    if c == '[':
        current_l = []
    elif c == ",":
        if current_l is not None:
            current_l.append(int(current_n))
            current_n = ''
    elif c.isdigit():
        current_n += c
    elif c == "]":
        current_l.append(int(current_n))
        l.append(current_l)
        current_n = ''
        current_l = None

l1, l2  = l
print(l1, l2)
# [4, 2, 1, 5, 7] [45, 1, 2, 3, 5, 7, 100, 2, 7]

Not something you would typically do, but a good exercise and it's simplicity should make is quite fast.

Upvotes: 1

DYZ
DYZ

Reputation: 57033

I would suggest "disguising" the input as a well-formed list by adding the outer brackets and then using literal_eval:

import ast
s = "[4,2,1,5,7],[4,1,2,3,5,7,1,2,7]"
parts = ast.literal_eval("[" + s + "]")
#[[4, 2, 1, 5, 7], [4, 1, 2, 3, 5, 7, 1, 2, 7]]

Or do not add anything and treat the input as a tuple of lists:

parts = ast.literal_eval(s)
#([4, 2, 1, 5, 7], [4, 1, 2, 3, 5, 7, 1, 2, 7])

Upvotes: 2

Related Questions