Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert strings within an array to list in Python

I want to convert the array A containing string elements to list. But I am running into error while using split(). I present the expected output.

import numpy as np
from numpy import nan
A=np.array(['[1]', '[2]',  '[3]', '[4]', '[5]'])
A.split()
print(A)

The error is

in <module>
    A.split()

AttributeError: 'list' object has no attribute 'split'

The expected output is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

array([[1], [2], [3], [4], [5]])

>Solution :

I think this should work

A=np.array(['[1]', '[2]',  '[3]', '[4]', '[5]'])
output = [[int(a.strip("[|]"))] for a in A]
print(output)
[[1], [2], [3], [4], [5]]

if you prefer just an list, instead of a list of list

A=np.array(['[1]', '[2]',  '[3]', '[4]', '[5]'])
output = [int(a.strip("[|]")) for a in A]
print(output)
[1, 2, 3, 4, 5]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading