1

I have an array like below;

constants = ['(1,2)', '(1,5,1)', '1']

I would like to transform the array into like below;

constants = [(1,2), 1, 2, 3, 4, 5, 1]

For doing this, i tried some operations;

from ast import literal_eval
import numpy as np
constants = literal_eval(str(constants).replace("'",""))
constants = [(np.arange(*i) if len(i)==3 else i) if isinstance(i, tuple) else i for i in constants]

And the output was;

constants = [(1, 2), array([1, 2, 3, 4]), 1]

So, this is not expected result and I'm stuck in this step. The question is, how can i merge the array with its parent array?

4
  • 1
    why isn't the first tuple converted? Commented Aug 10, 2018 at 11:49
  • I don't need convert it. I need to convert tuples has 3 values. Commented Aug 10, 2018 at 11:50
  • Doesn't np.arange(1,5,1) return np.array([1, 2, 3, 4])? Commented Aug 10, 2018 at 11:51
  • @taras Yes it does. But it's not my problem. The problem is how to merge it with parent array. Commented Aug 10, 2018 at 11:52

4 Answers 4

1

This is one approach.

Demo:

from ast import literal_eval

constants = ['(1,2)', '(1,5,1)', '1']
res = []
for i in constants:                
    val = literal_eval(i)              #Convert to python object
    if isinstance(val, tuple):         #Check if element is tuple
        if len(val) == 3:              #Check if no of elements in tuple == 3
            val = list(val)
            val[1]+=1
            res.extend(range(*val))
            continue            
    res.append(val)
print(res)

Output:

[(1, 2), 1, 2, 3, 4, 5, 1]
Sign up to request clarification or add additional context in comments.

5 Comments

what if the array: constants = ['(1,2)', '(1,5,1)', '1', '(0.1, 0.9, 0.1)'] ? The error is: 'float' object cannot be interpreted as an integer.
What is the expected output of ['(1,2)', '(1,5,1)', '1', '(0.1, 0.9, 0.1)'] ?
The expected result: [(1,2), 1, 2, 3, 4, 5, 1, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
I solved it; just change the range(*val) to np.arange(*val).
Yes...I was about to post that :)
0

I'm going to assume that this question is very literal, and that you always want to transform this:

constants = ['(a, b)', '(x, y, z)', 'i']

into this:

transformed = [(a,b), x, x+z, x+2*z, ..., y, i]

such that the second tuple is a range from x to y with step z. So your final transformed array is the first element, then the range defined by your second element, and then your last element. The easiest way to do this is simply step-by-step:

constants = ['(a, b)', '(x, y, z)', 'i']
literals = [eval(k) for k in constants]    # get rid of the strings
part1 = [literals[0]]                      # individually make each of the three parts of your list
part2 = [k for k in range(literals[1][0], literals[1][1] + 1, literals[1][2])]    # or if you don't need to include y then you could just do range(literals[1])
part3 = [literals[2]]
transformed = part1 + part2 + part3

Comments

0

I propose the following:

res = []
for cst in constants:

    if isinstance(cst,tuple) and (len(cst) == 3):
        #add the range to the list
        res.extend(range(cst[0],cst[1], cst[2]))
    else:
        res.append(cst)

res has the result you want. There may be a more elegant way to solve it.

Comments

0

Please use code below to resolve parsing described above:

from ast import literal_eval


constants = ['(1,2)', '(1,5,1)', '1']
processed = []

for index, c in enumerate(constants):
    parsed = literal_eval(c)
    if isinstance(parsed, (tuple, list)) and index != 0:
        processed.extend(range(1, max(parsed) + 1))
    else:
        processed.append(parsed)

print processed  # [(1, 2), 1, 2, 3, 4, 5, 1]

4 Comments

TypeError: isinstance expected 2 arguments, got 3
The result is not i wanted. The result should be; [(1,2), 1, 2, 3, 4, 5, 1]
@AndriyIvaneyko, what if a tuple is not the first element of the list?
@taras item will be appended.

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.