Concatenate items in a vector

0

I have the following vector, which I get after querying a database:

a = ['[[10, 20], 10]']

When I try to access their values through the indexes, I can not.

For example, if you type: print(a[0][0]) . Returned '['

I've tried to do: b = ''.join(a) print. However, this situation continues.

I need this vector to be "really" converted to a vector.

For example, if I wanted to query the value [10, 20] , I would print(a[0]) . If you want to see 20%, print(a[0][1])

I have tried many solutions (with join, numpy and etc ...). Could someone help me?

    
asked by anonymous 12.10.2017 / 01:09

2 answers

3

What you are getting from the database seems to be a list of just a string value, so you will not be able to access the values as if it were a list. What you can do, and works for this particular case, is to convert your string to a list via a JSON parser:

import json

a = ['[[10, 20], 10]']

lista = json.loads(a[0])

print(lista[0])    # [10, 20]
print(lista[0][1]) # 20

But if this is coming from the database, there are serious indications that your tables are poorly structured.

    
12.10.2017 / 01:19
3

The return you get from the database is a string that represents the syntax of a Python list, not a list itself. To use it as a list, you need Python to interpret the snippet of code it represents, and to do that there are a few options.

ast.literal_eval ()

Considering that the string contains Python code and it is a literal structure ( string , number , tuple , list , dict , boolean , or None ), you can use the ast.literal_eval() function. The ast library enables the programmatic interpretation of Python syntax, so that the function in question receives a literal structure string and returns it interpreted at runtime:

>>> import ast
>>> retorno = '[[10, 20], 10]'
>>> a = ast.literal_eval(retorno)
>>> print(a[0][0])
10
>>> print(a[0][1])
20

(example in repl.it: link )

json.loads ()

Since your parse string example also represents a JSON array, you can use the JSON parser Python to interpret it safely, as shown by @ anderson-carlos-woss in the accepted response:

>>> import json
>>> retorno = '[[10, 20], 10]'
>>> a = json.loads(retorno)
>>> print(a[0][0])
10
>>> print(a[0][1])
20

(example in repl.it: link )

yaml.safe_load

Parsers of other serialization languages that use JSON arrays, such as the YAML (

12.10.2017 / 01:18